Welcome, guest | Sign In | My Account | Store | Cart

A simple example which shows how to implement your own JSP custom tag with the help of Jython.

Python, 23 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# DemoTag.py

from javax.servlet.jsp.tagext import TagSupport

class DemoTag(TagSupport):

    def __init__(self):
        self.context = None
        self.parentTag = None

    def doStartTag(self):
        out = self.context.out
        out.print("Hello World from Jython Tag.")
        return self.SKIP_BODY

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

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

    def getParent(self):
        return self.parentTag

Setup instructions:

(1) generate and compile java class from Jython source jythonc -p jythonsupport DemoTag.py (make sure you have jython.jar available on your CLASSPATH)

(2) put the generated java byte code to the {webapp}/WEB-INF/classes/jythonsupport directory

(3) define the new jython tag in your tag library descriptor file (TLD) add the following fragment

< tag > < name > jydemo < /name > < tag-class > jythonsupport.DemoTag < /tag-class > < body-content > EMPTY < /body-content > < description > A demo custom tag written in Jython. < /description > < /tag >

(4) write a 'normal' JSP using the new tag :-)

[Tested this with Tomcat 4.0.3 / JDK 1.4 / Jython 2.1]

1 comment

Don Rivard 20 years, 10 months ago  # | flag

does this really work? I cannot get this code to work. Using Jython 2.1 Tomcat 4.1. I get the following errors:

C:\Tomcat 4.1\work\Standalone\localhost\jythontest\jython_jsp.java:74: cannot resolve symbol symbol : method setPageContext (javax.servlet.jsp.PageContext) location: class jythonsupport.DemoTag _jspx_th_app_jydemo_0.setPageContext(pageContext); ^ C:\Tomcat 4.1\work\Standalone\localhost\jythontest\jython_jsp.java:75: cannot resolve symbol symbol : method setParent (I cannot get this code to work. Using Jython 2.1 Tomcat 4.1. I get the following errors:

C:\Tomcat 4.1\work\Standalone\localhost\jythontest\jython_jsp.java:74: cannot resolve symbol symbol : method setPageContext (javax.servlet.jsp.PageContext) location: class jythonsupport.DemoTag _jspx_th_app_jydemo_0.setPageContext(pageContext); ^ C:\Tomcat 4.1\work\Standalone\localhost\jythontest\jython_jsp.java:75: cannot resolve symbol symbol : method setParent (

Created by Niko Schmuck on Fri, 15 Mar 2002 (PSF)
Python recipes (4591)
Niko Schmuck's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks