IBM Skip to main content
Search for:   within 
      Search help  
     IBM home  |  Products & services  |  Support & downloads   |  My account

developerWorks > Java technology | Web architecture
J2EE pathfinder: Implement JSP custom tags in five easy steps
Discuss152 KBe-mail it!
JSP custom tags
Implementing JSP custom tags
Step 1. Write the tag handler class
Step 2. Create the TLD
Step 3. Make the TLD and handler class accessible
Step 4. Reference the library
Step 5. Use the tag in a JSP page
Save time with the JSTL
About the author
Rate this article
Related content:
Intro to taglibs
JSP architecture
A JSTL primer
J2EE pathfinder series
IBM developer kits for Java (downloads)
dW newsletters
dW Subscription
(CDs and downloads)
A hands-on introduction to using custom tags in your JSP pages

Level: Introductory

Kyle Gabhart ( JSP custom tags in five easy steps)
Consultant, Gabhart Communications
22 October 2003

Column iconJSP custom tags provide a standardized mechanism for separating presentation and business logic in a dynamic Web page, allowing page designers to focus on presentation while application developers code the back end. In this installment of J2EE pathfinder, enterprise-minded developer Kyle Gabhart introduces the basics of JSP custom tags and takes you through the five-step process of incorporating them into your JSP pages.

You've probably heard it said a hundred different ways by now, but it really is important to separate presentation logic and business logic when you're developing a Web application. In recent years, the Java platform has evolved to incorporate this separation at the architectural level. For example, the inclusion of JavaBeans components within the JSP architecture lets developers use JSP tags to get and set properties on specially coded Java components. These components, or JavaBeans, then perform back-end business processing on behalf of the presentation tier.

JSP custom tags are an outgrowth of the JSP/JavaBean architecture. Like JavaBeans technology, custom tags facilitate the separation of presentation logic and business logic. Moreover, custom tags act as a bridge between the Web designer's world of HTML, XML, and Javascript, and the software engineer's world of Java code, SQL calls, and algorithms.

In this month's J2EE pathfinder, you'll learn some of the basics of using JSP custom tags in your JSP pages. We'll start with an introduction to JSP tags, and then launch directly into the process of creating a tag, incorporating it into the JSP container, and using it in a JSP page. At the end of the article we'll briefly discuss the Java Standard Tag Library (JSTL), a set of standardized JSP custom tags for use in your Java development projects.

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:

  1. Write the tag handler class.
  2. Create the tag library descriptor (TLD).
  3. Make the TLD file and handler classes accessible.
  4. Reference the tag library.
  5. 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.

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 BodyTagSupport class). 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

Notes about the code
Several things are worth noting about the DateTag handler class. First, take a look at the method declarations. If we were to directly implement the Tag interface, we would need to fulfill several method declarations. Because the TagSupport class is a simple, concrete class that fully implements the methods declared in the Tag interface, we are free to implement only those methods that we want to use for our custom tag. In this simple example, we've implemented only the doStartTag() method, which is invoked when the start tag is encountered.

You may also note that the doStartTag() method returns SKIP_BODY. The reason, of course, is that our simple date tag has no body. The final important thing you may note is that a pageContext object is used to access the output buffer for sending content directly to the output stream. As you may recall from the previous installment in this series, the pageContext object is an implicit object that provides access to attributes relating to the current page.

After writing the source code file, we simply compile the class as we would any other Java class (being sure to include the Servlet/JSP JAR files in the classpath), and then place the compiled class file in the Web application's classes directory (WEB-INF/classes). If we were developing several tags or defining tags with tag variables, we would have multiple tag handler classes. In that case we might opt to package our handler classes in a JAR file rather than dumping them as loose files into the class directory.

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" ?>

   <info>A simple tag library</info>

    <info>Display Date</info>

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" ?>

   <!-- Define Servlets, Servlet Mappings, etc. -->

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" %>

Static versus dynamic referencing
When you make a static reference to your taglib, the JSP declaration must query the web.xml file to perform a library lookup. This means that if you move or rename the library or want to add additional libraries to the web.xml file, you must stop the server, update the web.xml file, and then restart the server. The dynamic approach has the JSP page point directly to the location of the TLD and is therefore processed at JSP page translation time.

The static approach provides a level of indirection between your pages and the actual name and location of your libraries, which can provide you with some flexibility to change these attributes without modifying your pages. On the other hand, the dynamic approach provides more flexibility, allowing you to add and remove tag declarations at run time. If the dynamic approach appeals to you, but you are wary of the potential maintenance headache of updating multiple pages whenever something changes, you could always place your JSP declaration(s) into a separate JSP file that you include in each page that will access your Web app's custom libraries. This gives you the flexibility to add libraries at run time while still only having to update the information once.

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:

Listing 3. JSP page with a custom tag

<%@ taglib uri="/WEB-INF/lib/DateTagLib.tld"  prefix="abc" %>
    <TITLE>Date tag example</TITLE>
    <H1>Date tag Example</H1>
    <p>Hi today is <b><abc:displayDate /></b> </p>

Boot up your Web server and test out the JSP page for yourself! The results should look similar to those shown in Figure 1.

Figure 1. Browser output of DateTag
Browser output of DateTag

Save time with the JSTL
Perhaps as much as 80 percent of the custom tag functionality that you will need has already been created and standardized by the J2EE community. You can save yourself a significant amount of time and energy by using an existing tag library rather than creating everything from scratch. Although there are dozens and dozens of tag libraries available in the public domain, the industry has rallied around one particular custom tag library. The Java Standard Tag Library (JSTL) was designed by the Java Community Process and its reference implementation is developed and maintained by The Apache Group through the Jakarta Taglibs project (see Resources).

The JSTL defines tags addressing common Web application processing requirements such as variable support, flow control, URL management, XML manipulation, internationalization, database access, and more. In addition to a rich set of tags, the JSTL defines its own expression language (EL). The EL gives us easy access to application data and makes it easy to manipulate that data without scriptlets or request-time expressions.

In addition to saving you the time and energy of developing all your tags from scratch, the JSTL comes with all the benefits of standardization and industry acceptance. These include vendor support, a wealth of instructional literature, and a strong chance of finding employees or contractors with previous JSTL experience.

In the ongoing quest for technical solutions that separate business and presentation logic in J2EE Web development, JSP custom tags offer a compelling alternative to plain old JavaBeans and Java scriptlets. Of further benefit is the existence of the standard set of custom tag libraries defined within the JSTL. In this installment of J2EE pathfinder, you've walked through the process of creating a custom tag from scratch and implementing it in a JSP page. I've also provided a brief intro to the JSTL and outlined the benefits of using it rather than creating all your custom tags from scratch.

Next month, we'll continue our exploration of J2EE technology with a foray into J2EE's Web application security architecture. Until then, happy pathfinding!


About the author
Photo of Kyle GabhartKyle Gabhart is an independent consultant and subject matter expert with J2EE, XML, and Web services technologies. Kyle is a popular public speaker, recognized for his enthusiasm and dynamic analysis and presentation of emerging technologies. For information on his recent and upcoming presentations or industry publications, visit Kyle can be reached at

Discuss152 KBe-mail it!

What do you think of this document?
Killer! (5) Good stuff (4) So-so; not bad (3) Needs work (2) Lame! (1)

Send us your comments or click Discuss to share your comments with others.

developerWorks > Java technology | Web architecture
  About IBM  |  Privacy  |  Terms of use  |  Contact