Running a Servlet with Jython
Credit: Brian Zhou
Problem
You need to code a servlet using Jython.
Solution
Java (and Jython) is most often deployed server-side, and thus servlets are a typical way of deploying your code. Jython makes them easy to use:
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( )
returnDiscussion
This is no worse than a typical JSP! (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. Note that most of
your setup work will be strictly related to Tomcat or whatever
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 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 ...