Using Jython servlets with WebSphere Application Server for more than system administration

It is common for developers to use Jython scripting in IBM® WebSphere® Application Server to perform system management tasks, but with some simple additions, it is easy to add Jython processing to supplement your servlet and JSP application programming. This article describes what you need to do to incorporate Jython servlets into your projects for even greater flexibility. This content is part of the IBM WebSphere Developer Technical Journal.


Brian S Paskin (, Senior WebSphere Consultant, IBM

Brain Paskin is a veteran of IBM for 18 years and has worked for IBM in Germany, Italy and the US. He is currently working for IBM Software Services for WebSphere helping customers with WebSphere MQ, WebSphere Application Server, DataPower implementation, performance, and other issues. Brian has helped write two IBM Redbooks and is certified on several IBM products.

25 January 2012

Also available in Chinese Russian


Jython is the Java™ implementation of the scripting language Python. Within IBM WebSphere Application Server, is often used to make changes to the environment, start and stop application servers, and automate the performance of other administrative tasks. In addition, Jython can also be used as a replacement for or in addition to servlet and JSP application programming. The ability to add Jython servlets to WebSphere Application Server provides yet another tool that can provide valuable flexibility to your projects.

Jython is an interpreted language that is compiled when executed. Changes can be made quickly and easily to Jython scripts, and so new functionality can be quicky added to an existing project. Jython can reference its own modules and Java classes, which makes it very flexible.

Jython and Python interoperability

At a given time, the Jython language might not be at the same release level as Python. Anything that has been added in Python since the current release level of Jython cannot be used and will result in errors or warnings.

The version of Jython that is embedded within WebSphere Application Server does not contain the full implementation of the language. To get that, you must download the full version from the Jython website. As of this writing, the most current version of Jython is version 2.5.2. After downloading the code, expand it to a location on your system; for example, C:\$user\jython-2.5.2.

The sections that follow describe what you need to do to incorporate and use Jython servlets in applications you are developing for use with WebSphere Application Server V7.x and V8.0.

Project creation and setup

  1. Create the web project.

    In IBM Rational® Application Developer or Eclipse, create a new dynamic web project. For the purpose of this example, the web project is called JythonTest is not assigned to an enterprise archive (Figure 1). Click Finish to create the new project.

    Figure 1. Create web project
    Figure 1. Create web project
  2. Add the necessary libraries.

    The Jython library and a WebSphere Application Server library need to be associated with the project. Right-click on the project and select Properties. Select Java Build Path from the list in the left column (Figure 2).

    Figure 2. Add libraries to build path
    Figure 2. Add libraries to build path

    The Libraries tab, selected in Figure 2, shows the current list of libraries that are associated with the project. The Jython and WebSphere Application Server libraries will need to be added to the list. To do this, click Add External JARS... and then navigate to the location of these libraries (Figures 3 and 4); the Jython library is located under <jython_home>/jython.jar, and the WebSphere Application Server library is located under <was_home>/lib/j2ee.jar. Click the Open button to add the library to the Java Build Path for the project (do this for each library).

    Figure 3. Add Jython JAR file
    Figure 3. Add Jython JAR file
    Figure 4. Add J2EE JAR file
    Figure 4. Add J2EE JAR file

    When finished, the project property’s Java Build Path panel should look similar to that shown in Figure 5. Click OK to save the information.

    Figure 5. Confirm build path
    Figure 5. Confirm build path
  3. Adding the PyServlet.

    Next, you need to configure your project’s web.xml file to accept the Jython servlet, which is called PyServlet. To do this, expand the project in the Enterprise Explorer on the left side of the Rational Application Developer panel. The web.xml file is located at JythonTest > WebContent > WEB-INF. Double click on the web.xml file to display the Web Application Deployment Descriptor Editor, and click the Source tab.

    Instead of using the wizards to add the Jython servlet, use the code shown in Listing 1 as an example for setting up the mappings to the servlet and to make the servlet load upon start of the application server. This should not change very much from project to project.

    Listing 1
    		<description>Default Servlet for Jython</description>

    What this code does is set up a servlet called PyServlet, assigns it to the class org.python.util.PyServlet, and makes sure that it loads itself upon starting of the application server. The mappings take any request that ends ".py” and calls the PyServlet for processing.

Jython scripting in WebSphere Application Server

Your web application is now set up to accept Jython scripts and execute them using PyServlet. All you need now is to create the content that will be executed. As an example, below is a first, very basic script to show how quickly a Jython script can be written.

Due to the Jython code being in a script, you need to add a file to your project. In the Package Explorer, expand the Project view until the WebContent folder is visible. Right click on the WebContent folder and select New > File. In the dialog that displays (Figure 6), enter for File name and click Finish.

Figure 6. Add new file
Figure 6. Add new file

A new tab with a blank page will appear ready for entry. Enter the script code shown in Listing 2 and save it.

Listing 2
from javax.servlet.http import HttpServlet 

class welcome (HttpServlet): 
	def doGet(self,request,response): 
		self.doPost (request,response) 
	def doPost(self,request,response): 
		output = response.getWriter() 
		response.setContentType ("text/html") 
		output.println ("<html><head><title>Welcome!</title><body>
			<h1>Welcome to your first Jython Servlet</h1></body></html>")

This should look very similar to servlet programming. In fact, the class is extending the HttpServlet class like any servlet would do in Java. Jython uses white space for its scoping and is dynamically typed, unlike Java. The code is similar to Java in a few ways: the code imports the HttpServlet class from Java, has two exposed methods (doGet and doPost), and sends back a response to the request in HTML format.

Java and Jython working together

Here is another simple example to show how Java and Jython can work together, and how Jython can be quicker to code in some instances.

This Get List example uses a JSP, a Jython servlet, and a text file for data, which contains a list of names. This example shows the interaction between the JSP and Jython servlet and how it is really no different than a regular servlet.

Create another new file, using the same procedure shown above, this time called guestlist.jsp. Copy and paste the code shown on Listing 3. This JSP is the display page for entering the name of a guest and an indicator showing the response of whether or not the person was found on the guest list.

Listing 3
		<title>Guest List</title>
		<style>h3 { color: red; }</style>
		<h1>Guest List</h1>
		<form action="" method="post">
			Guest's Name : <input type="text" name="guestName" 
				size="20" maxlength="20" /> 
			<input type="submit" name="submit" value="Check List" />
				if (request.getAttribute("msg") != null)

This sample JSP contains nothing fancy; there is a form that will call the Jython servlet,, and pass the name of the guest entered in the text box. It will also display a message from the Jython servlet, if one is available.

Create one more new file called and copy in the code from Listing 4. This is the Jython servlet that will read the guest list text file and determine if the name passed to it is in the file. A message will be sent back to the JSP with the result.

Listing 4
# import from Java
from javax.servlet.http import HttpServlet

# import from Jython
import os

class guestlist (HttpServlet):
	# global variables
	global fileName
	global guestFile
	global dispatcher
	fileName = "guestlist.txt"

	# Standard HTTPServlet init function
	def init(self,config):
		# The guest list file is located side the war file that was create
		# and the application will need direct access to read the file
		# for processing later.  This is how to get the path to the file.
		global guestFile
		guestFile = config.getServletContext().getRealPath("/") + os.sep 
			+ fileName

		# Get the request dispatcher.  This example only has 1 
		# jsp page so it can be static
		global dispatcher
		dispatcher = config.getServletContext().getRequestDispatcher
	# Standard HTTPServlet doGet function.
	# Nothing to do except pass the request to the doPost function
	def doGet(self,request,response): 
		self.doPost (request,response) 

	# Standard HTTPServlet doPost function
	def doPost(self,request,response): 
		# check to see if the the guestName parameter
		# was passed in the request. If not then forward
		# to the jsp.
    		guestName = request.getParameter("guestName")
		if guestName is None:
    		# Read the file to see if the name is on
    		# the list that was sent from the jsp
    		onList = self.checkGuestList(guestName)

		# If the name sent from the jsp is on the
		# list then send a found message otherwise
		# send a not found message
    		if onList:
			request.setAttribute("msg",guestName + " found on the list")
    			request.setAttribute("msg",guestName + " NOT found on the list")

		# forward the request onto the JSP

	# Function to read the guest list and see if the person
	# is on the guest list
	def checkGuestList(self,guest):
		# Try to open the file for reading and then go line by line
		# to see if the line matches the guest's name that was passed
		# to the function.  Lines in files end in a return ("\n") and
		# this must be accounted for while doin the comparison.
		# Returns true if found or false if not found
		f = open(guestFile, 'r')
		for line in f:
			if line == guest + "\n":
				return True
		return False

One thing to notice is that none of the variables are typed or need to be initialized, which is different from Java programming. The Jython servlet is using the init function to get the file path, but is doing so by using both Java and Jython elements. The checkGuestList function reads the file using Jython functions rather than Java classes, and does so with far less code.

Finally, create one last new file called guestlist.txt and copy in the names from Listing 5 (or you can place your own names in the file). Each name must end with a line feed or it might not match what is sent from the JSP.

Listing 5

The guest list will be placed within the web archive to make it a static location for the example.

This simple example is useful in showing some of the similarities and differences between Jython and Java, how you can use both together or separately when needed, and how coding in Jython can be done rather quickly.

Setting up WebSphere Application Server

  1. Preparing WebSphere Application Server.

    Each instance of WebSphere Application Server that will be using Jython will need two items added to the classpath plus a custom property:

    • For the classpath, the first item is the location of Jython itself. The second is the location of the j2ee.jar file provided with WebSphere Application Server.
    • The custom property will tell the JVM where the home directory of Jython is located.

    In the WebSphere Integrated Solutions Console (ISC), navigate to Application Servers > <Application Server Name> > Process Definition > Java Virtual Machine. In the text box marked Classpath under General Properties, add the two items shown in Listing 5 (Figure 7) and click OK. This will add these two Java libraries to the WebSphere Application Server startup.

    Listing 5
    Figure 7. Add JAR files to JVM
    Figure 7. Add JAR files to JVM

    Next, you need to tell Jython where its home directory is located on the server. Do this by adding a custom property to each of the application servers that will be using Jython. Navigate to Application Servers > <Application Server Name> > Process Definition > Java Virtual Machine > Custom Properties and click New. In the Name field enter python.home, and in the Value field enter the base directory of where Jython is installed (Figure 8). Click OK when done.

    Figure 8. Find Jython home directory
    Figure 8. Find Jython home directory

    These changes must be replicated to all nodes. For the changes to then take effect, you must restart all application servers.

  2. Installing the application.

    You can package and export the application from Rational Application Developer. From the Enterprise Explorer in Rational Application Developer, right-click on the project and select Export > WAR file (Figure 9).

    Figure 9. Export WAR file
    Figure 9. Export WAR file

    This will cause a model window to be displayed (Figure 10). Enter the destination where the WAR file should be saved and click Finish.

    Figure 10. Save WAR file
    Figure 10. Save WAR file

    Once the application is exported, it can be installed in WebSphere Application Server. Logon to the WebSphere Integrated Solutions Console and navigate to Applications > New Application > New Enterprise Application. Use the Browse button to select the .ear or .war file that was exported from Rational Application Developer and then click Next (Figure 11).

    Figure 11. Install application
    Figure 11. Install application

    On the next panel (Figure 12), select Fast Path and then Next. Select Next on the panels that follow until the Map context roots for Web modules panel displays (Figure 13).

    Figure 12. Install using Fast Path
    Figure 12 Install using Fast Path
    Figure 13. Map context roots for Web modules
    Figure 13. Map context roots for Web modules

    For the Context Root, enter /jython. Click Next until the Summary panel displays (Figure 14), then click Finish.

    Figure 14. Summary
    Figure 14. Summary

    After the application is deployed properly, Save it (Figure 15).

    Figure 15. Successful installation
    Figure 15. Successful installation

    Once the application is deployed, you can start the application server and test the application. To test the application, open a browser and navigate to http://hostname:port/jython/, where hostname is the hostname or IP address of the application server where the application is deployed, and the port is the HTTP port that the application server is listening on. A welcome message should be display (Figure 16).

    Figure 16. Welcome panel
    Figure 16. Welcome panel

    Check the guest list servlet by changing the name of the servlet to (that is, localhost:9080/jython/ The guest list web page should display (Figure 17). Enter a person’s name and click Check List to see the response. A message should display indicating whether or not the person is found in the file (Figures 18 and 19).

    Figure 17. Enter guest name
    Figure 17. Enter guest name
    Figure 18. Result: Record not found
    Figure 18. Result: Record not found
    Figure 19. Result: Record found
    Figure 19. Result: Record found


With some simple additions, it is easy to add Jython processing to your regular WebSphere Application Server processing. This can be done together with Java or alone, but either way it can add flexibility and efficiency to your current WebSphere Application Server environment. In addition, including Jython also enables users who are not familiar with Java to contribute Jython programs to the processing environment.



developerWorks: Sign in

Required fields are indicated with an asterisk (*).

Need an IBM ID?
Forgot your IBM ID?

Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.


All information submitted is secure.

Dig deeper into WebSphere on developerWorks

ArticleTitle=Using Jython servlets with WebSphere Application Server for more than system administration