Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
344
Chapter 14 Creating Custom JSP Tag Libraries
Now, suppose that we want to define a set of tags that would be used like
this:
<%= someExpression %>
JSP to include if condition is true
JSP to include if condition is false
To accomplish this task, the first step is to define an 
IfTag
 class to handle
the 
csajsp:if
 tag. This handler should have methods to specify and check
whether the condition is true or false (
setCondition
 and 
getCondition
) as
well as methods to designate and check if the condition has ever been explic 
itly set (
setHasCondition
 and 
getHasCondition
), since we want to disal 
low 
csajsp:if
 tags that contain no 
csajsp:condition
 entry. Listing 14.23
shows the code for 
IfTag
.
The second step is to define a tag handler for 
csajsp:condition
. This
class, called 
IfConditionTag
, defines a 
doStartTag
  method  that  merely
checks if the tag appears within 
IfTag
. It returns 
EVAL_BODY_TAG
 if so and
throws an exception if not. The handler's 
doAfterBody
 method looks up
the body content (
getBodyContent
), converts it to a 
String
 (
getString
),
and compares that to 
"true"
. This approach means that an explicit value of
true
 can be substituted for a JSP expression like 
<%= expression %>
 if,
during initial page development, you want to temporarily designate that the
then
 portion should always be used. Using a comparison to 
"true"
 also
means that any other value will be considered  false.  Once this compari 
son is performed, the result is stored in the enclosing tag by means of the
setCondition
 method of 
IfTag
. The code for 
IfConditionTag
 is shown
in Listing 14.24.
The third step is to define a class to handle the 
csajsp:then
 tag. The
doStartTag
 method of this class verifies that it is inside 
IfTag
 and also
checks that an explicit condition has been set (i.e., that the 
IfConditionTag
has already appeared within the 
IfTag
). The 
doAfterBody
 method checks
for the condition in the 
IfTag
 class, and, if it is true, looks up the body con 
tent and prints it. Listing 14.25 shows the code.
The final step in defining tag handlers is to define a class for 
csa 
jsp:else
. This class is very similar to the one to handle the 
then
 part of
the tag, except that this handler only prints the tag body from 
doAfterBody
if the condition from the surrounding 
IfTag
 is false. The code is shown in
Listing 14.26. 
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

jsp web hosting

 

Our partners: PHP: Hypertext Preprocessor Best Web Hosting Java Web Hosting Jsp Web Hosting Cheapest Web Hosting

Visionwebhosting.net Business web hosting division of Web Design Plus. All rights reserved