JSP Tag Libraries

Скачать в pdf «JSP Tag Libraries»


IfTag will also need to implement some conditional logic inside dostartTag() once it gets the JavaBean property. Our IfTag will only look at the value of the object or property it received in its attributes, convert the value to a boolean, and, if the boolean value is true, evaluate the tag’s body into the response. Implementing this logic is no problem if the value on which we base our condition is already boolean; in other cases we just convert the value to a boolean. For IfTag, we’ve chosen an extremely simple conversion logic (since the goal of the tag is to demonstrate conditional execution, not necessarily data-type conversion).


With this in mind, let’s take a look at IfTag’s implementation.


Listing 9.1 Source code for IfTag handler


package book.conditions;


import javax.servlet.jsp.PageContext; import javax.servlet.jsp.JspException;


import book.util.LocalStrings; import book.reflection.ReflectionTag;


public class IfTag extends ReflectionTag {


static LocalStrings ls =


LocalStrings.getLocalStrings(IfTag.class);


public int doStartTag()


throws JspException


{


boolean b = evalBoolean(getPointed());


if(null != id) {


pageContext.setAttribute(id,


new Boolean(b), PageContext.PAGE_SCOPE);


} if(b) {


return EVAL_BODY_INCLUDE


}


return SKIP_BODY;


}


protected boolean evalBoolean(Object o)


{


if(o instanceof Boolean) {


return ((Boolean)o).booleanValue();


}


if(o instanceof Number) {


return ((Number)o).intValue() != 0;


}


return new Boolean(o.toString()).booleanValue();


}


}

B Sends the pointed variable (our condition) to boolean evaluation.
C Based on the returned value includes the body (if true) or excludes it (false).
D Evaluates the condition value as boolean (the simple way).


There is nothing too complex in implementing IfTag. All the reflection work is implemented by ReflectionTag and the rest of the work is actually evaluating the pointed value as a boolean and whether to include the tag’s body in the response (returning eval_body_include) or exclude it (returning skip_body).

Скачать в pdf «JSP Tag Libraries»