background image

Tag Handlers for Tags with Bodies

<< Setting Deferred Value Attributes | Tags That Define Variables >>
<< Setting Deferred Value Attributes | Tags That Define Variables >>

Tag Handlers for Tags with Bodies

If you have an attribute that is both dynamic and deferred (meaning that the tag attribute
definition accepts a deferred expression and has rtexprvalue set to true), then the setX
method that accesses this value must accept an Object instance and test if the Object instance is
a deferred value expression, as shown in this pseudocode:
public void setAttr(Object obj) {
if (obj instance of ValueExpression) {
// this is a deferred expression
else {
// this is an rtexpression
}
}
Tag Handlers for Tags with Bodies
A simple tag handler for a tag with a body is implemented differently depending on whether or
not the tag handler needs to manipulate the body. A tag handler manipulates the body when it
reads or modifies the contents of the body.
Tag Handler Does Not Manipulate the Body
If a tag handler needs simply to evaluate the body, it gets the body using the getJspBody
method of SimpleTag and then evaluates the body using the invoke method.
The following tag handler accepts a test parameter and evaluates the body of the tag if the test
evaluates to true. The body of the tag is encapsulated in a JSP fragment. If the test is true, the
handler retrieves the fragment using the getJspBody method. The invoke method directs all
output to a supplied writer or, if the writer is null, to the JspWriter returned by the getOut
method of the JspContext associated with the tag handler.
public class IfSimpleTag extends SimpleTagSupport {
private boolean test;
public void setTest(boolean test) {
this.test = test;
}
public void doTag() throws JspException, IOException {
if(test){
getJspBody().invoke(null);
}
}
}
Programming Simple Tag Handlers
The Java EE 5 Tutorial · September 2007
260