What is a Custom Tag?
Custom Tag is an action tag defined by the user through the JSP tag extension facility. It can be used to move JSP page authoring logics and information into a tag Java class, and invoke it by an action tag that is linked to that class. There are two main advantages of using custom tags:
- Repeatable JSP page logics and information can be simplified and centralized into a single tag. For example, we can define a custom tag called <my:copyright/> for producing the copyright information that need to be used on every page of server.
- Moving complex business logics from the JSP to a tag class, so the JSP page author can concentrate on the presentation logics only. For example, we can define a custom tag called <my:userList/> for producing a HTML table filled with a list of users. The tag class will manage how the put each user into a row, and each user property into a column.
JSP custom tags
A JSP custom tag is a user-defined tag that follows a special XML syntax used by the JSP JavaBean tags (that is,
useBean,getProperty, and setProperty). When a custom tag is processed by the servlet container, one or more Java class files are invoked to process it, in much the same way that a Java class file is used to handle JavaBean calls for a JSP page. When the tag is processed, the container will take its name and attributes, as well as any content that may exist in the body of the tag, and pass it to one or more class files for handling.Java developers write the tag handler classes to process the tags and handle all of the Java coding and data manipulation required. To a Web designer, custom tags look and smell just like standard HTML tags, except that they are able to leverage dynamic data on the back end. Properly written custom tags can allow a Web designer to create, query, and operate on data without having to write a single line of Java code. Properly executed, custom tags free Java developers from having to incorporate the presentation layer into the coding process. In this way each member of the application development team is able to focus on what he or she does best.
Implementing JSP custom tags
The JSP architecture requires the following components to implement custom tags:
- A JSP declaration in each page
- An entry in the Web application descriptor (web.xml)
- A JAR file containing a special XML file and the Java classes that will be invoked to process the custom tags
In the sections that follow, you'll learn, step-by-step, how to meet these requirements and incorporate custom tags into your JSP pages. Here are the five steps between you and a successful JSP custom tag implementation:
- Write the tag handler class.
- Create the tag library descriptor (TLD).
- Make the TLD file and handler classes accessible.
- Reference the tag library.
- Use the tag in a JSP page.
This stuff is pretty basic and it won't take long, so let's get started.
Step 1. Write the tag handler class
Throughout the examples that follow, we'll work with a very simple custom tag that displays the current time and date. Here is the
DateTag:<abc:displayDate />
|
The first thing we need to do is write the tag handler class. The JSP container evaluates each custom tag during the execution of a JSP page that references it. When the container encounters a tag, it invokes the tag handler class associated with the custom tag, which is a process we'll talk more about later. Every tag handler then implements a special interface from the JSP API. There are two types of tags: those that can process the content (or body) of a tag and those that cannot:
<abc:tagWithNoBody attribute="value"/>
<abc:tagWithBody attribute="value">
This is some body content that the tag handler can operate upon.
</abc:tagWithBody>
|
We do not need to include body content in our example
DateTag, because it only displays the current date. As such, our handler class will implement the Tag interface (typically by extending the TagSupport class). If we were to create a tag capable of processing body content, we would need to implement the BodyTag interface (typically by extending the BodyTagSupportclass). Listing 1 shows the handler class for our DateTag:Listing 1. Tag handler class
package myTags;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import javax.servlet.http.*;
import java.text.*;
import java.util.*;
public DateTag extends TagSupport {
public int doStartTag() throws javax.servlet.jsp.JspException {
HttpServletRequest req;
Locale locale;
HttpJspPage g;
DateFormat df;
String date;
JSPWriter out;
req = ( HttpServletRequest )pageContext.getRequest();
locale = req.getLocale();
df = SimpleDateFormat.getDateInstance(
SimpleDateFormat.FULL,locale );
date = df.format( new java.util.Date() );
try {
out = pageContext.getOut();
out.print( date );
} catch( IOException ioe ) {
throw new JspException( "I/O Error : " + ioe.getMessage() );
}//end try/catch
return Tag.SKIP_BODY;
}//end doStartTag()
}//end DateTag
|
Step 2. Create the TLD
Our next step is to define the library that will contain the mappings between our custom tag and the Java class (or classes) that will handle it. This library is defined within an XML document called a tag library descriptor (TLD). We'll call the TLD for our
DateTag example DateTagLib.tld. Note that ".tld" is the standard extension for such files.Listing 2. The DateTagLib.tld file
<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib>
<tlibversion>1.0</tlibversion>
<info>A simple tag library</info>
<tag>
<name>displayDate</name>
<tagclass>myTags.DateTag</tagclass>
<bodycontent>empty</bodycontent>
<info>Display Date</info>
</tag>
</taglib>
|
DateTagLib.tld is an excellent, minimal tag library descriptor file. All key information is contained within the
Tag tag where the tag name and handler class are mapped, and we've made a declaration regarding the tag's sensitivity to body content. In more complex cases we could use additional XML tags to provide more information about the library and about the tags. It would also be typical to define multiple tags within a single library.Step 3. Make the TLD and handler class accessible
The third step is to make the class or classes and TLD accessible to the Web application. There are two ways of doing this. We can either package the classes and TLD together into a JAR file and then store the JAR file in the Web application's lib directory, or we can place the class files loosely in the classes subdirectory and place the TLD file somewhere beneath the Web application's WEB-INF directory.
For this example, we'll use the second approach, placing the TLD file and classes loosely within the Web application directory structure. You will recall that we have already placed the tag handler class in the classes directory, in Step 1, so we actually only have to store the TLD file. TLD files are stored in the WEB-INF directory or subdirectory or, in the case of a JAR file deployment, in the META-INF/ directory or subdirectory of the JAR. In this case, we're not using a JAR file, so we'll simply store our TLD in the Web application's WEB-INF/lib directory.
Step 4. Reference the library
Thus far, we've written a tag handler class, created a TLD file to define the mapping between the handler and the tag, and ensured that both the class and tag will be accessible within the application. The next step is to establish a reference between our JSP pages and the tag library. There are two ways to declare a reference between a JSP page and its library. We can declare a static reference through our Web application descriptor (web.xml), or declare a dynamic reference directly within the page. We'll try them both.
To make a static reference, we must first add the following entry to the web.xml file:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<Web-app>
<!-- Define Servlets, Servlet Mappings, etc. -->
<taglib>
<taglib-uri>myTags</taglib-uri>
<taglib-location>/WEB-INF/lib/DateTagLib.tld</taglib-location>
</taglib>
</Web-app>
|
Next, we add a JSP declaration to any page that will need to use the custom tag library:
<%@ taglib uri="myTags" prefix="abc" %>
|
Note that the
uri attribute that is specified matches the taglib-uri value specified in the web.xml file.To make a dynamic reference, we simply add a JSP declaration to any page that needs to use the library:
<%@ taglib uri="/WEB-INF/lib/DateTagLib.tld" prefix="abc" %>
|
Step 5. Use the tag in a JSP page
With all the prep work behind us, we're ready to use our custom tag within a JSP page. Listing 3 shows the browser output of a JSP page that contains the
DateTag:JSP page with a custom tag
<%@ taglib uri="/WEB-INF/lib/DateTagLib.tld" prefix="abc" %> <HTML> <HEAD> <TITLE>Date tag example</TITLE> </HEAD> <BODY> <H1>Date tag Example</H1> <p>Hi today is <b><abc:displayDate /></b> </p> </BODY> </HTML> |
Figure 1. Browser output of DateTag
Posted in: