Home > Articles > Open Source > Python

  • Print
  • + Share This
  • 💬 Discuss
This chapter is from the book

This chapter is from the book

JSP

Java Server Pages (JSP) is the templating system espoused by Sun as a compliment to Servlets. A JSP file contains a web page's markup code and text unaltered, but also contains special tags that designate dynamic content. Currently, Tomcat only implement the Java language in JSP, so the big question is how do you use Jython with JSP. Currently, the answer is that you do not use Jython directly. You cannot include a code tag (<% code %>) where the code is in the Jython language. What you can do is use jythonc-compiled classes, use an embedded PythonInterpreter, or create a Jython-specific, custom tag library.

jythonc-Compiled Classes and JSP

Using jythonc-compiled classes with JSP requires creating a Java-compatible Jython class. One that has the same name as the module within it, inherits from a Java class, and includes @sig strings for each method not derived from the superclass. Placing class files generated with jythonc in the context's classes directory allows JSP pages to use those classes just like any native Java class. Of course, this also requires that the jython.jar file is placed in the context's lib directory.

A JSP file can use a jythonc-compiled class one of two ways, in scriptlets, or as a bean. If it is to be used as a bean, the Jython class must comply with bean conventions and include a getProperty and setProperty method for each read-write property. A scriptlet, however, can use any class. Whether as a bean or in a scriptlet, you must first load the jythonc-compiled class into the appropriate scope. To import a non-bean class, use the page import directive:

<%@ page import="fully.qualified.path.to.class" %>

For a bean, use the jsp:useBean tag to load the bean:

<jsp:useBean name="beanName"
       class="fully.qualified path.to.class"
       scope="scope(page or session)">

To use a non-bean class, include Java code using that class in scriplet tags (<% %>) or in expression tags (<%= %>). If you imported the hypothetical class ProductListing, you could use that class in something similar to the following contrived JSP page:

<%@ page import="ProductListing" %>

<html>
<body>

<!––The next line begins the scriptlet ––>
<% ProductListing pl = new ProductListing(); %>

<table>
 <tr>
  <td><%= pl.productOne %></td>
  <td><%= pl.productTwo %></td>
 </tr>
</table>

Scriplets are often discouraged because they complicate the JSP page. The preferred implementation uses jythonc-compiled beans along with the JSP useBean, setProperty, and getProperty tags. Listing 12.10 is a very simple bean written in Jython that stores a username. It will serve as an example on how to use a bean written in Jython.

Listing 12.10 A Simple Bean Written in Jython

# file: NameHandler.py
import java

class NameHandler(java.lang.Object):
  def __init__(self):
    self.name = "Fred"
  def getUsername(self):
    "@sig public String getname()"
    return self.name
  def setUsername(self, name):
    "@sig public void setname(java.lang.String name)"
    self.name = name

Place the nameHandler.py file from Listing 12.10 in the %TOMCAT_HOME%\webapps\jython\WEB-INF\classes directory and compile it from within that directory with the following command:

jythonc –w . Namehandler.py

Listing 12.11 is a simple JSP page that uses the NameHandler bean.

Listing 12.11 Using a Jython Bean in a JSP page

<!––file: name.jsp ––> 
<%@ page contentType="text/html" %>

<jsp:useBean id="name" class="NameHandler" scope="session"/>

<html>
<head>
 <title>hello</title>
</head>
<body bgcolor="white">
Hello, my name is

<jsp:getProperty name="name" property="username"/>
<br>

No, wait...

<jsp:setProperty name="name" property="username" value="Robert"/>

, It's really <%= name.getUsername() %>.

</body>
</html>

Notice that the jsp:setProperty does the same as the <%= beanName.property = value %> expression and the jsp:getProperty is the same as the <%= beanName.property %> expression.

To use the JSP page in Listing 12.11, place the name.jsp file in the context's root directory (%TOMCAT_HOME%\webapps\jython), and then point your browser to http://localhost:8080/jython/name.jsp. You should see the default name Fred and the revised name Robert.

Embedding a PythonInterpreter in JSP

If you did wish to use Jython code within a JSP scriptlet, you could indirectly do so with a PythonInterpreter instance. This would require that you use an import directive to import org.python.util.Pythoninterpreter. Listing 12.12 shows a simple JSP page that uses the PythonInterpreter object to include Jython code in JSP pages.

Listing 12.12 Embedding a PythonInterpreter in a JSP Page

<!––name: interp.jsp––>
<%@ page contentType="text/html" %>
<%@ page import="org.python.util.PythonInterpreter" %>

<% PythonInterpreter interp = new PythonInterpreter();
  interp.set("out, out); %>


<html>
<body bgcolor="white">
<% interp.exec("out.printIn('Hello from JSP and the Jython interpreter.')"); %>
</body>
</html>

To use the interp.jsp file, make sure that the jython.jar file is in the context's lib directory, and place the interp.jsp file in the context's root directory (%TOMCAT_HOME%\webapps\jython). If you then point your browser at http://localhost:8080/jython/interp.jsp you should see the simple message from the Jython interpreter.

Note that many consider scriptlets poor practice anyway, so adding another level of complexity by using Jython from Java in scriptlets is obviously suspect. There are better ways to create dynamic content, such as bean classes and taglibs.

A Jython Taglib

Taglibs are custom tag libraries that you can use within JSP pages. You can create taglibs in Jython by using jythonc to compile Jython taglib modules into Java classes. A Jython taglib module must then comply with certain restrictions before it transparently acts as a Java class. The module must contain a class with the same name as the module (without the .py extension). The class must subclass the javax.servlet.jsp.tagext.Tag interface or a Java class that implements this interface. The org.python.* packages and classes, and Jython library modules (if the taglib imports any) must be accessible to the compiled class file.

To make all the required classes and libraries available to a taglib, you can compile it with jythonc's ––all option much like was done with jythonc-compiled Servlets earlier in this chapter. Doing so would create a jar file that you would then place in the context's lib directory. The problem is that it is very likely that numerous resources will use the Jython core files, so repeatedly compiling with ––core, ––deep, or ––all creates wasteful redundancy. The better plan is to include the jython.jar file in the context's lib directory, establish a Jython lib directory for Jython's modules somewhere in the context ({context}\WEB-INF\lib\Lib is recommended—see the earlier section "PyServlet" for an explanation), and then compile the Jython taglib modules without dependencies.

Listing 12.13 is a simple Jython taglib module that serves as the specimen used to dissect taglibs. All Listing 12.13 does is add a message, but it implements all the essential parts of a taglib. The basic requirements implemented in Listing 12.13 are as follows:

  • The name of the file in Listing 12.13 is the same as the class it contains.

  • The class implements (subclasses) the javax.servlet.jsp.tagext.Tag interface. Other options for the superclass (interfaces) include the BodyTag and IterationTag interfaces, and the TagSupport or BodyTagSupport classes from the javax.servlet.jsp.tagext package.

  • The JythonTag class implements all the methods required to complete the Tag interface.

Listing 12.13 A Jython Taglib

# file: JythonTag.py
from javax.servlet.jsp import tagext

class JythonTag(tagext.Tag):
  def __init__(self):
    self.context = None
    self.paren = None

  def doStartTag(self):
    return tagext.Tag.SKIP_BODY

  def doEndTag(self):
    out = self.context.out
    print >>out, "Message from a taglib"
    return tagext.Tag.EVAL_PAGE

  def release(self):
    pass

  def setPageContext(self, context):
    self.context = context

  def setParent(self, parent):
    self.paren = parent

  def getParent(self):
    return self.paren

The instance variables holding the pageContext and parent tag information (self.context and self.paren) deserve a special warning. These variables either must not be identified as self.pageContext and self.parent, or all access to these variables must go through the instance's __dict__. The Tag interface requires that implementations of the setPageContext(), setParent(), and getParent() methods, but because these methods exist, Jython creates an automatic bean property for their associated property names. This makes circular references and StackOverflowExceptions easy to make. Imagine the following code:

def setPageContext(self, context):
  self.context = context

The setPageContext method assigns the context to the instance attribute self.context. However, self.context is an automatic bean property, meaning that self.context really calls self.setPageContext(context). This type of circular reference is always a concern when using jythonc-compiled classes in Java frameworks, but it is the explicit requirement of get* and set* methods due to the interface that increases the likelihood here.

To install the classes required for the taglib in Listing 12.13, first ensure the jython.jar file is in the context's lib directory, then compile the JythonTag.py file with the following command:

jythonc –w %TOMCAT_HOME%\webapps\jython\WEB-INF\classes JythonTag.py

This will create the JythonTag.class and JythonTag$_PyInner.class files in the context's classes directory. The classes themselves are insufficient to use the taglib, however. You must also create a taglib library description file before using the tag in a JSP page. Listing 12.14 is a taglib library description file appropriate for describing the tag defined in Listing 12.13.

Listing 12.14 Tag Library Descriptor

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
 PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
 "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">

<taglib>
  <tlibversion>1.0</tlibversion>
  <jspversion>1.1</jspversion>
  <shortname>JythonTag</shortname>
  <info>A simple Jython tag library</info>
  <tag>
    <name>message</name>
    <tagclass>JythonTag</tagclass>
  </tag>
</taglib>

Place the tag library descriptor information from Listing 12.14 in the file %TOMCAT_HOME%\webapps\jython\WEB-XML\jython-taglibs.tld. JSP pages will use this file to identify tags used within the page.

The tag library descriptor identifies characteristics of the tag library such as its version number, and the version of JSP it is designed for. It also specifies a name <shortname> for referencing this tag library. The remaining elements define the one specific tag library created in listing 12.13. The tag element identifies the fully qualified class name and assigns a name to that class. The JythonTag is not in a package, so it is a fully qualified name on its own, and this class is associated with the name taglet.

With JythonTag compiled and the tag library descriptor saved, that remaining step is to use the tag library from a JSP page. A JSP page must include a directive that designates the path to the tag library descriptor and assigns a simple name that library. All subsequent references to tags within this library will begin with the name assigned in this directive. A JSP directive for the tag library created in Listings 12.13 and 12.14 would look like the following:

<%@ taglib uri="/WEB-INF/jython-taglibs.tld" prefix="jython" %>

Remember that the .tld file specified the name message for our example tag, so after declaring this tag library, you may subsequently use the message tag with the following:

<jython:message/>

The jython portion of the tag comes from the name assigned in the JSP declaration, while the message portion comes from a tag class's assigned name as specified in the tag library description. Listing 12.15 is a JSP file that uses the tag defined in Listing 12.13 and the taglib descriptor in Listing 12.14. Save the test.jsp file in Listing 12.14 as %TOMCAT_HOME%\webapps\jython\test.jsp, then point your browser to http://localhost:8080/jython/test.jsp, and you should see the custom tag message.

Listing 12.15 A JSP File that Employs the JythonTag

<%@ taglib uri="/WEB-INF/jython-taglibs.tld" prefix="jython" %>
<html>
<body>

<jython:message />

</body>
</html>

Implementing taglibs with compiled jython modules again raises issues with Jython's home directory and Jython's lib directory. A jythonc-compiled taglib will not know where python.home is or where to find library modules unless that information is established in the PySystemState. You can set the python.home property in the TOMCAT_OPTS environment variable, but you could also leverage the PyServlet class to establish this system state information. If the context you are in loads the PyServlet class, then the python.home and sys.path information may already be correct for the taglibs that need it. With the default PyServlet settings, python.home is %TOMCAT_HOME%\webapps\ jython\WEB-INF\lib, and therefore Jython's lib directory is %TOMCAT_HOME%\webapps\jython\WEB-INF\lib\Lib. With PyServlet loaded, taglibs may load Jython modules from the same lib directory.

BSF

IBM's Bean Scripting Framework (BSF) is a Java tool that implements various scripting languages. Jython is one of the languages that BSF currently supports. The Apache Jakarta project includes a subproject called taglibs, which is an extensive collection of Java tag libraries ready for use; however, the interesting taglib is the BSF tag library. The BSF tag library combined with the BSF jar file itself allows you to quickly insert Jython scriptlets and expression directly into JSP pages.

The BSF distribution currently requires a few tweaks to work with Jython. Because the BSF distribution will eventually include these small changes, there is no advantage to detailing them here; however, this does mean you need to confirm your version of BSF includes these changes. To make this easy, the website associated with this book (http://www.newriders.com/) will include a link to where you can download the correct bsf.jar file. After downloading the bsf.jar file, place it in the context's lib directory (%TOMCAT_HOME%\ webapps\jython\WEB-INF\lib). The website associated with this book will also contain download links for the BSF taglibs and bsf.tld files. Place the jar file containing the BSF taglibs in the context's lib directory, and place the bsf.tld file in the context's WEB-INF directory (%TOMCAT_HOME%\webapps\jython\WEB-INF\bsf.tld).

With these files installed, you can use Jython scriptlets within JSP files. You first must include a directive to identify the BSF taglib:

<%@ taglib uri="/WEB-INF/bsf.tld" prefix="bsf" %>

Then you can use the bsf.scriptlet tag, including Jython code in the tag body like so:

<bsf.scriptlet language="jython">
import random
print >>, out random.randint(1, 100)
</bsf.scriptlet>

The scriptlet has a number of JSP objects automatically set in the interpreter, and these objects are listed below with their Java class names:

  • request javax.servlet.http.HttpServletRequest
  • response javax.servlet.http.HttpServletResponse
  • pageContext javax.servlet.jsp.PageContext
  • application javax.servlet.ServletContext
  • outjavax.servlet.jsp.JspWriter
  • config javax.servlet.ServletConfig
  • page java.lang.Object
  • exception java.lang.Exception
  • session javax.servlet.http.HttpSession

Most of the objects are familiar from Servlets, but the BSF scriptlet tag lets you use them within JSP pages. Listing 12.16 shows a JSP page that uses the bsf:scriptlet tag to create a timestamp in a JSP file.

Listing 12.16 BSF Scriptlet

<%@ taglib uri="/WEB-INF/bsf.tld" prefix="bsf" %>
<html>
<body>

<center><H2>BSF scriptlets</H2></center>

<b>client info:</b><br>

<bsf:scriptlet language="jython">
for x in request.headerNames:
  print >>out, "%s: &nbsp;%s<br>\n" % (x, request.getHeader(x))
</bsf:scriptlet>

<br><br>
<b>Time of request:</b><br>

<bsf:scriptlet language="jython">
import time
print >>out, time.ctime(time.time())
</bsf:scriptlet>

</body>
</html>

After saving Listing 12.16 as the file %TOMCAT_HOME%\webapps\jython\scriptlets.jsp, point your browser to http://localhost:8080/jython/scriptlets.jsp. You should see all the client information as well as the access time.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus