Home > Articles > Open Source > Python

This chapter is from the book

This chapter is from the book

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:

  1. Compile the Jython Servlet module with jythonc.

  2. Add the jython.jar file to the web application.

  3. 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020