- Jython Servlet Containers
- Defining Simple Servlet Classes
- More About GenericServlet
- HttpServlet
- PyServlet
- Cookies
- Sessions
- Databases and Servlets
- JSP
Defining Simple Servlet Classes
This section compares a simple Java Servlet with a simple Jython Servlet. The section on testing these Servlets describes how to install the jython.jar file in a Tomcat web application.
A Simple Java Servlet
Listing 12.1 is the most basic of Java Servlets.
Listing 12.1 A Basic Java Servlet
""'// Filename: JavaServlet.java import javax.servlet.*; import java.io.*; public class JavaServlet extends GenericServlet { public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter toClient = res.getWriter(); toClient.println("<html><body>" + "This is a Java Servlet." + "</body></html>"); } }
A base class from the Servlet API is required, and Listing 12.1 uses GenericServlet, imported from the javax.servlet package in the first line. The service method in GenericServlet is abstract, so it must be implemented in any subclasses. This is the method invoked in response to a web request for JavaServlet (the name of the file in Listing 12.1). Output destined for the client is sent through a PrintWriter object retrieved from the ServletResponse object. This could also be an OutputStream for binary data.
A Simple Jython Servlet
Implementing a Jython Servlet comparable to Listing 12.1 should be similar in what it imports, inherits, and implements, but done in Jython's syntax. Listing 12.2 demonstrates.
Listing 12.2 A Basic Jython Servlet
# Filename: JythonServlet.py from javax import servlet import random # Not used, just here to test module imports class JythonServlet(servlet.GenericServlet): def service(self, req, res): res.setContentType("text/html") toClient = res.getWriter() toClient.println("""<html><body> This is a Servlet of the Jython variety. </body></html>""")
Listing 12.2 is a subclass of GenericServlet just like its Java counterpart in Listing 12.1. It also implements the service() method of GenericServlet as required. Syntactic differences in Listing 12.2 include parentheses after the class definition to designate the superclass, the omission of the throws statement, an explicit self parameter in the service method, and, of course, the absence of semicolons and explicit type declarations. Additionally, the import statements differ in Jython. As stated earlier, the from module import * syntax is strongly discouraged; instead, Listing 12.2 imports the parent package. One additional import in Listing 12.2 is the random module. This module is not actually used, and only exists to test module imports.
Testing the Java and Jython Servlets
Testing the Servlets in Listings 12.1 and 12.2 requires the installation of Tomcat. The Jython Servlet in Listing 12.2 additionally requires including the jython.jar file in Tomcat. This section first describes the steps to installing Tomcat, then addresses the installation and testing of the two Servlets discussed.
Installing Tomcat
The first step is to download Tomcat from http://jakarta.apache.org. This section addresses the installation of a binary release of Tomcat in stand-alone mode. The suggested version to download is jakarta-tomcat-3.2.3. Download the zip or tar.gz file appropriate for your platform.
Next, unzip or untar the archive to the directory in which you have sufficient permissions. If you unzip the archive into the C:\jakarta-tomcat-3.2.3 directory, this becomes the Tomcat home directory. If you use /usr/local/jakarta-tomcat-3.2.3, this becomes the Tomcat home directory. You should set an environment variable to the Tomcat home directory. For the directory C:\jakarta-tomcat-3.2.3 on Windows, add the following to your environment settings:
set TOMCAT_HOME=c:\jakarta-tomcat-3.2.3
For the directory /usr/local/jakarta-tomcat-3.2.3 on *nix, add the following to your bash environment:
export TOMCAT_HOME=/usr/local/jakarta-tomcat-3.2.3
If you do not set the TOMCAT_HOME environment variable, you must start Tomcat from within its home or bin directory.
Next, set the environment variable JAVA_HOME to the root directory of your JDK installation. Here's an example using JDK1.3.1:
# on Windows set JAVA_HOME=c:\jdk1.3.1 # bash (*nix) setup export JAVA_HOME=/usr/java/jdk1.3.1
The installation is complete. You can start Tomcat with the startup script appropriate for your platform:
# Windows %TOMCAT_HOME%\bin\startup.bat # bash (*unix) $TOMCAT_HOME/bin/startup.sh
You should see startup information printed to the screen as the Tomcat server loads. An important line to look for is this:
date time - PoolTcpConnector: Starting HttpConnectionHandler on 8080
This designates the port that you will be using to connect to the Servlet container: 8080 is the default. When you see this, Tomcat is running and ready to accept connections on port 8080.
When you wish to stop Tomcat, use the following shutdown scripts:
# Windows %TOMCAT_HOME%\bin\shutdown.bat # bash (*nix) $TOMCAT_HOME/bin/shutdown.sh
The Servlet 2.2 specification designates a directory hierarchy for web applications that begins in the directory %TOMCAT_HOME%\webapps. Folders within this directory are web applications, or contexts, and each follows a specific directory hierarchy. The examples in this chapter use the context named jython. The directory structure required for the jython context is shown here:
%TOMCAT_HOME%\webapps\ %TOMCAT_HOME%\webapps\jython The context's root %TOMCAT_HOME%\webapps\jython\WEB-INF %TOMCAT_HOME%\webapps\jython\WEB-INF\classes Servlet classes %TOMCAT_HOME%\webapps\jython\WEB-INF\lib Library archives
You should create these directories before continuing with the examples. If you restart Tomcat, you should see an additional line of information when it restarts. The following line confirms that Tomcat has loaded the new context:
date time - ContextManager: Adding context Ctx( /jython )
Installing the Java Servlet
To install the Java Servlet from Listing 12.1, first place the JavaServlet.java file in the directory %TOMCAT_HOME%\webapps\jython\WEB-INF\classes. This directory is the root directory for class files. Because JavaServlet is not within a package, it belongs in the root of the classes directory. Note that Listing 12.1 is not within a package; if you had chosen to designate a package, such as the package demo for example, you would have then placed the compiled class file in the classes\demo directory in order to comply with Java class directory structures. This is only a note for those Servlets placed within a package, which is not the case for our example, however.
From within that directory, compile the JavaServlet.java file with the following command:
javac -classpath %TOMCAT_HOME%\lib\servlet.jar JavaServlet.java
After compiling JavaServlet, you are ready to view it. First, start the Tomcat server, and then point your browser to http://localhost:8080/jython/servlet/JavaServlet. You should see the simple string message This is a Java Servlet.
Installing the Jython Servlet
There are two ways to use Jython Servlets. One is to compile the Servlet with jythonc and place the resulting class files in the %TOMCAT_HOM%\jython\WEB-INF\classes directory. The other is to use Jython's PyServlet mapping class. This section uses jythonc. The PyServlet mapping is often a better way to deploy Jython Servlets, but jythonc-compiled Servlets are equally sensible at times.
The three steps required to install a jythonc-compiled Servlet in Tomcat are as follows:
Compile the Jython Servlet module with jythonc.
Add the jython.jar file to the web application.
Make the modules from Jython's lib directory available to Jython Servlets.
Compiling a Jython Servlet with jythonc
Compiling with jythonc requires that the servlet.jar file exists within the classpath. The servlet.jar file contains the javax.Servlet.* classes and packages, and it is found in Tomcat's lib directory (%TOMCAT_HOME%\lib). If you use jythonc to compile a Servlet without servlet.jar in the classpath, there are no errors or warnings during the compilation; however, when you try to run a Servlet compiled that way, you will get a java.lang.ClassCastException (at least that is the case for jythonc at the time of this writing).
Place the JythonServlet.py file from Listing 12.2 to the directory %TOMCAT_HOME%\jython\WEB-INF\classes. Ensure that your environment CLASSPATH variable does in fact include Servlet.jar, and then use jythonc to compile the Jython code into Java classes by using the following command from within the %TOMCAT_HOME%\jython\WEB-INF\classes directory:
jythonc w . JythonServlet.py
Specifying the current working directory with the w switch eliminates the need to copy the generated class files from the jpywork directory. There should be two class files in the classes directory. Remember that a compiled Jython file will have at least two associated class files. The files produced from compiling JythonServlet.py with jythonc should be JythonServlet.java, JythonServlet.class, and JythonServlet$_PyInner.class. Both the class files are required to use the Servlet and must both be in the WEB-INF\classes directory.
During the compilation with jythonc, it is important to look for the lines that read as follows:
Creating .java files: JythonServlet module JythonServlet extends javax.servlet.GenericServlet
If you do not see these lines, something is wrong and the Servlet will not work. Double-check the CLASSPATH and setup options and compile the file again until you see the lines noted previously.
Adding jython.jar to the classpath
All Jython Servlets must have access to the classes within the jython.jar file. There are three ways to add the jython.jar file to Tomcat's classpath:
Add jython.jar to the context's lib directory. This is the preferred way.
Add jython.jar to Tomcat's lib directory. This method is discouraged.
Leave jython.jar in Jython's installation directory, but add it to the classpath before running Tomcat. This is reasonable, but not as good as placing it in the context's lib directory.
The preferred approach is to place the jython.jar file in the context's lib directory. The context should include the directory {context}\WEB-INF\lib. For the jython context used in this chapter, it is %TOMCAT_HOME%\webapps\jython\WEB-INF\lib. Class archive files, such as jython.jar, belong in this directory. This is preferred because it makes a self-contained web application. As soon as a web application requires access to archives outside of its context, archiving, packaging, and installing the application on other servers becomes troublesome. You are strongly urged to keep all web applications self-contained unless you are sure it is not necessary in your situation.
You can also place the jython.jar file in Tomcat's lib directory (%TOMCAT_HOME%\lib). Jar files in this directory are automatically added to the classpath. However, this is the least preferred of the three approaches. You may reduce duplicate jython.jar files, but your web application is no longer self-contained. Additionally, you do not get automatic access to Jython's lib directory as you do with the third approach.
The third option is to leave the jython.jar file in Jython's installation directory, and add it to the classpath before starting Tomcat. This also eliminates duplicate jython.jar files; however, it has the added advantage of providing access to the registry file and Jython's lib directory. Remember that the registry is sought in the python.home directory, or in the location in which the jython.jar file was found if there is no python.home property. Leaving the jython.jar file in Jython's installation directory is therefore an advantage over placing it in Tomcat's lib directory. It's worth mentioning again, however, that a self-contained context is preferred.
Making Jython's lib Directory Available to Servlets
There are three ways to make the modules in Jython's lib directory available to Servlets:
Set the python.home property.
Freeze required modules.
Have each Servlet explicitly append module locations to the sys.path.
If you chose to leave the jython.jar file in Jython's installation directory, no additional steps are required to gain access to Jython's lib directory. If you chose to place the jython.jar file in the context's lib directory, you must set the python.home property, explicitly append a directory to sys.path, or freeze the modules before your Jython Servlets can use the Jython module library.
To set the python.home property you can set the TOMCAT_OPTS environment variable. Before you do this, you must decide where the modules will be located. Again, the best way is to create a self-contained web application. A good recommendation is to create an additional directory within the context's WEB-INF directory. The name of this directory will be jylib for the purposes of this section. Create the directory %TOMCAT_HOME%\webapps\jython\WEB-INF\jylib. Because Jython looks for the lib directory within python.home, continue by also making the directory %TOMCAT_HOME%\webapps\jython\ WEB-INF\jylib\Lib. Place any required modules within this directory, and specify the jylib directory as the python.home. Here are some examples that set TOMCAT_OPTS to the proper python.home property setting:
# Windows set TOMCAT_OPTS=-Dpython.home=%TOMCAT_HOME%\webapps\jython\WEB-INF\jylib # bash (*nix) export TOMCAT_OPTS=-Dpython.home=$TOMCAT_HOME/webapps/jython/WEB-INF/jylib
Note that some versions of Windows do not allow an equals sign in an environment string. In this case, you must edit the tomcat.bat file to include the python.home parameter setting.
It is possible to just begin Servlets by explicitly adding the module directory to sys.path. The problem is that this often requires explicit, machine-dependent paths, and thus limits cross-platform portability. Here is an example of what would appear at the top of a Servlet where you wish to explicitly append to the sys.path:
import sys libpath = "c:/jakarta-tomcat_3.2.3/webapps/jython/WEB-INF/jylibs/Lib" sys.path.append(libpath)
Another useful approach to making Jython's modules available is to freeze them. The jythonc deep option compiles all required modules, making the python.home and Jython's lib directory unimportant. To freeze the JythonServlet.py file from Listing 12.2, use the following command from within the Jython context's classes directory:
jythonc w . deep JythonServlet.py
Class files for the JythonServlet and for all the modules it requires are now located within the context's classes directory. In other words, the Servlet and modules are now installed in a self-contained web application. Note that compiling other Jython Servlets this way will overwrite any previously compiled modules. This means you must be careful when updating modules, as a newer version may adversely affect an older Servlet. Compiling with the deep options creates a number of files, but the generated *.java files may be deleted after compilation.
Freezing is beneficial because changes to modules are infrequent, and because it is an easy way to make a fully self-contained web application. You don't need to set the python.home property. A web application set up this way can simply be archived as a .war file and plugged into any other compliant server without a single extra installation step required.
Testing the Jython Servlet
With the Servlet from Listing 12.2 compiled with jythonc, the jython.jar in the classpath, and Jython's modules accessible, you can now view it. Point you browser to http://localhost:8080/jython/servlet/jythonServlet. You should see the simple message "This is a Servlet of the Jython variety." If this is not what you see, the likely alternatives are one of three error messages. If the Servlet.jar file was not in the classpath while compiling the JythonServlet, you will likely see a ClassCastException. You will also see a ClassCastException if the filename and classname differ, even if only in capitalization. If one of the class files generated from compiling the Servlet with jythonc is in the context's classes directory, you will see an AttributeError. If Jython's modules are not available, you will see an ImportError.