Wednesday, July 26, 2006

Jython Custom JSP Tags

I just tried to create a custom JSP Tag based on this sample. After compiling it with jythonc I relaized that the doStartTag() method had no throws in it's declaration which was a problem to javac. So I had to use an intermediate BaseTag class that provides a handleStartTag() method without throwing an explicit exception. I also added some sig-strings to the jython code.

The resulting JSP can access all implicit variables like this:


<jy:eval expr="request.getAttribute('now')"/>
<jy:eval expr="session"/>
<jy:eval expr="session.getAttribute('name')"/>
<jy:eval expr="pageContext"/>
<jy:eval expr="request.session"/>





Here are the sources:



========= JythonEvalTag.py =========

from samples import BaseTag

class JythonEvalTag(BaseTag):
"""Evaluates a jython expression.
Call it like <jy:eval expr="1+3"/>
or <jy:eval expr="request.getAttribute('blah')"/>"""

def handleStartTag(self):
"@sig public int handleStartTag()"
self.out.print(
eval(self.expr,
{'request':self.request,
'response':self.response,
'session':self.session,
'pageContext':self.pageContext}))
return self.SKIP_BODY

def setExpr(self, expr):
"@sig public void setExpr(String expr)"
self.expr = expr






========= BaseTag.java =========

package samples;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;

public abstract class BaseTag extends TagSupport {

/**
* Returns the page context.
*
* @return JSP pageContext implicit variable
*/

public PageContext getPageContext() {
return pageContext;
}

/**
* Returns the request.
*
* @return JSP request implicit variable
*/

public ServletRequest getRequest() {
return pageContext.getRequest();
}

/**
* Returns the response.
*
* @return JSP response implicit variable
*/

public ServletResponse getResponse() {
return pageContext.getResponse();
}

/**
* Returns the session.
*
* @return JSP session implicit variable
*/

public HttpSession getSession() {
return pageContext.getSession();
}

/**
* Returns the output writer.
*
* @return JSP out implicit variable
*/

public JspWriter getOut() {
return pageContext.getOut();
}

/*
* @see javax.servlet.jsp.tagext.Tag#doStartTag()
*/

public int doStartTag() throws JspException {
try {
return handleStartTag();
} catch (RuntimeException e) {
throw new JspException(e);
}
}

/**
* Handles tag functionality. This method does not throw an exception and
* thus can be overridden by jython classes using sig-strings.
*/

abstract public int handleStartTag();
}

No comments: