I l@ve RuBoard Previous Section Next Section

11.8 Running a Servlet with Jython

Credit: Brian Zhou

11.8.1 Problem

You need to code a servlet using Jython.

11.8.2 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(  )
        return

11.8.3 Discussion

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 similarly usable with Python (Jython) code. This example servlet needs to use 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 just 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.

11.8.4 See Also

Information on Java servlets at http://java.sun.com/products/servlet/; information on JythonServlet at http://jywiki.sourceforge.net/index.php?JythonServlet.

    I l@ve RuBoard Previous Section Next Section