07 Basic Custom Tags
07 Basic Custom Tags
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import java.math.*;
import coreservlets.Primes;
</BODY>
</HTML>
Attributes:
The Tag Handler Class
• Use of an attribute called attribute1
simply results in a call to a method called
setAttribute1
– Attribute value is supplied to method as a String
• Example
– To support
Attributes:
The Tag Library Descriptor File
• The tag element must contain a nested
attribute element
• The attribute element has three further-
nested elements
– name, a required element that defines the case-sensitive
attribute name.
– required, a required element that stipulates whether the
attribute must always be supplied (true) or is optional
(false).
– rtexprvalue, an optional attribute that indicates whether
the attribute value can be a JSP expression like
<%= expression %> (true) or whether it must be a fixed
string (false). The default value is false.
18 J2EE training: http://courses.coreservlets.com
TLD File for PrimeTag
...
<taglib ...>
...
<tag>
<description>Outputs an N-digit prime</description>
<name>prime</name>
<tag-class>coreservlets.tags.PrimeTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>length</name>
<required>false</required>
</attribute>
</tag>
...
</taglib>
</BODY>
</HTML>
Tag Files:
Custom Tags Using JSP Syntax
• Two Approaches
– When there is lots of logic, use Java to create output
• Analagous to when you use servlets
– When there is lots of formatting, use JSP to create output
• Analagous to when you use JSP pages
• Pros
– Very good for complex text formatting
– Very concise
• Cons
– Not good for complicated logic
– Runs only in JSP 2.0
• Java-based versions had "classic" syntax that worked in
36
older servers (e.g., BEA WebLogic 8.1, Oracle 9i AS)
J2EE training: http://courses.coreservlets.com
Simple Standalone Tags
• Java-based approach requires three pieces
– Java code that overrides doTag to generate output
• Strengths and weaknesses generally similar to those of
servlets, but more cumbersome
– Tag Library Descriptor (TLD) file that maps Java class
name to tag name
– JSP page that refers to specific location of TLD file
• JSP-based approach requires two pieces
– JSP code (tag file) that shows result
• /WEB-INF/tags/someName.tag
– No TLD file: tag name taken from tag-file name
– JSP page that refers to directory containing tag file
• /WEB-INF/tags or a subdirectory thereof
37 J2EE training: http://courses.coreservlets.com
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import java.math.*;
import coreservlets.Primes;
<tag>
<description>Outputs 50-digit primes</description>
<name>simplePrime</name>
<tag-class>coreservlets.tags.SimplePrimeTag</tag-class>
<body-content>empty</body-content>
</tag>
...
</taglib>
<%= coreservlets.Primes.nextPrime
(coreservlets.Primes.random(50)) %>
Questions?