How can I make a custom JSP tag that uses other JSP tags?

Maxy-B picture Maxy-B · Nov 1, 2011 · Viewed 8k times · Source

I would like to write a custom JSP tag whose output includes other JSP tags which should themselves also be dynamically evaluated. But apparently everything that my TagSupport subclass writes to pageContext.getOut() just goes straight to the client without any further evaluation.

I have a feeling this should be very simple, since it seems like one of the very first things one would want to use custom tags for: encapsulating and reusing other custom tags, avoiding code duplication.

How do I make the following code do what it obviously wants to do?:

public class MyTag extends TagSupport {
    public int doStartTag() throws JspException {
        try {
            pageContext.getOut().println(
              "The output from this tag includes other tags " +
              "like <mypackage:myOtherTag>this one</mypackage:myOtherTag> " +
              "which should themselves be evaluated and rendered."
            )
        } catch (IOException e) {
            throw new JspException(e);
        }
        return SKIP_BODY;
    }   
}

Edit: Some background on my particular use case, if it helps. I have a custom tag <user> which dynamically renders a user name in a way that is useful for my application (mouse-hover for first name, last name, phone number, etc.). I'm now writing another tag <comment> for displaying user comments, and I would like to use my existing <user> tag for rendering user names in the output of the <comment> tag.

Answer

JB Nizet picture JB Nizet · Dec 4, 2011

The easiest way is to write your custome tag as a JSP tag file, rather than in Java. This way, the new tag can use other custom tags easily. Create a file myTag.tag in /WEB-INF/tags, and use the following code:

<%@ tag %>
<%@ attribute name="value" required="true" rtexprvalue="true" type="java.lang.String"%>
<%@ taglib prefix="mypackage" uri="mypackage.tld" %>
The output from this tag includes other tags 
like <mypackage:myOtherTag>${value}</mypackage:myOtherTag>
which should themselves be evaluated and rendered.

More information about tag files here: http://docs.oracle.com/javaee/1.4/tutorial/doc/JSPTags5.html