Home > Articles > Open Source > Python

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020