Recipe 14.9. Running a Servlet with Jython
Credit: Brian Zhou
Problem
You need to code a servlet using Jython.
Solution
Java (and Jython) are most often deployed server-side, and thus
servlets are a typical way of deploying your code. Jython makes
servlets very easy to use. Here is a tiny "hello
world" example servlet:
import java, javax, sys
class hello(javax.servlet.http.HttpServlet):
def doGet(self, request, response):
response.setContentType("text/html")
out = response.getOutputStream( )
print >>out, ""<html>
<head><title>Hello World</title></head>
<body>Hello World from Jython Servlet at %s!
</body>
</html>
"" % (java.util.Date( ),)
out.close( )
return
Discussion
This recipe is no worse than a typical JSP (Java Server Page) (see
http://jywiki.sourceforge.net/index.php?JythonServlet
for setup instructions). Compare this recipe to the equivalent Java
code: with Python, you're finished coding in the
same time it takes to set up the framework in Java. Most of your
setup work will be strictly related to Tomcat or whichever servlet
container you use. The Jython-specific work is limited to copying
jython.jar to the
WEB-INF/lib subdirectory of your chosen servlet
context and editing WEB-INF/web.xml to add
<servlet> and
<servlet-mapping> tags so that
org.python.util.PyServlet serves the
*.py <url-pattern>.The key to this recipe (like most other Jython uses) is that your
Jython scripts and modules can import and use Java packages and
classes just as if the latter were Python code or extensions. In
other words, all of the Java libraries that you could use with Java
code are similarly usable with Python (i.e., Jython) code. This
example servlet first uses the standard Java servlet
response object to set the resulting
page's content type (to
text/html) and to get the output stream.
Afterwards, it can print to the output stream,
since the latter is a Python file-like object. To further show off
your seamless access to the Java libraries, you can also use the
Date class of the java.util
package, incidentally demonstrating how it can be printed as a string
from Jython.
See Also
Information on Java servlets at http://java.sun.com/products/servlet/;
information on JythonServlet at http://jywiki.sourceforge.net/index.php?JythonServlet.