background image

Tags That Define Variables

<< Tag Handlers for Tags with Bodies | TagExtraInfo Class >>
<< Tag Handlers for Tags with Bodies | TagExtraInfo Class >>

Tags That Define Variables

Tag Handler Manipulates the Body
If the tag handler needs to manipulate the body, the tag handler must capture the body in a
StringWriter
. The invoke method directs all output to a supplied writer. Then the modified
body is written to the JspWriter returned by the getOut method of the JspContext. Thus, a tag
that converts its body to uppercase could be written as follows:
public class SimpleWriter extends SimpleTagSupport {
public void doTag() throws JspException, IOException {
StringWriter sw = new StringWriter();
jspBody.invoke(sw);
jspContext().
getOut().println(sw.toString().toUpperCase());
}
}
Tag Handlers for Tags That Define Variables
Similar communication mechanisms exist for communication between JSP page and tag
handlers as for JSP pages and tag files.
To emulate IN parameters, use tag attributes. A tag attribute is communicated between the
calling page and the tag handler when the tag is invoked. No further communication occurs
between the calling page and the tag handler.
To emulate OUT or nested parameters, use variables with availability AT_BEGIN, AT_END, or
NESTED
. The variable is not initialized by the calling page but instead is set by the tag handler.
For AT_BEGIN availability, the variable is available in the calling page from the start tag until the
scope of any enclosing tag. If there's no enclosing tag, then the variable is available to the end of
the page. For AT_END availability, the variable is available in the calling page after the end tag
until the scope of any enclosing tag. If there's no enclosing tag, then the variable is available to
the end of the page. For nested parameters, the variable is available in the calling page between
the start tag and the end tag.
When you develop a tag handler you are responsible for creating and setting the object
referenced by the variable into a context that is accessible from the page. You do this by using
the JspContext().setAttribute(name, value) or
JspContext.setAttribute(name,value,scope)
method. You retrieve the page context using
the getJspContext method of SimpleTag.
Typically, an attribute passed to the custom tag specifies the name of the variable and the value
of the variable is dependent on another attribute. For example, the iterator tag introduced in
Chapter 5, "JavaServer Pages Technology"
retrieves the name of the variable from the var
attribute and determines the value of the variable from a computation performed on the group
attribute.
Programming Simple Tag Handlers
Chapter 8 · Custom Tags in JSP Pages
261