In this article will look at JSP Tag Libraries. We will look at using tag libraries for building JSP Page using custom tag libraries. This is the fourth article of five on JavaServer Pages. In the last article, “Tutorial:Review of JSP Actions for the Web Component Developer Exam”, we provided a review of JSP Actions and their use in building JSP Pages and JSP Documents. This is part of a series of articles to help you prepare for the web component developer exam.

What is a Custom Tag Library
Custom tag libraries are one of the key technologies that make JSP so powerful. They make it possible for web designers to provide rich layers of functionality and interactivity in a page using familiar, HTML-like elements. The JSP standard actions, such as the <jsp:useBean> and <jsp:getProperty> actions are HTML-like elements for commonly needed functions in a JSP page: creating beans, accessing bean properties, and invoking other JSP pages. Custom actions allow you to extend the set of action elements a web designer can use in the same familiar way. These new actions can be developed by a developer as a combination of Java classes and/or tag files. A custom action allows you a great deal of flexibility and power in terms of what you can do. You have access to all information about the request, you can add content to the response body as well as set response headers. And you can use any Java API to access external resources such as databases, LDAP servers, or mail servers.

The web container interacts with a custom action in a way that allows for the custom action to suspend the processing of the rest of the page while conditionally processing its body. You create custom actions for application-specific functions in order to make it easier for web designers to develop the JSP pages. A custom action can then be inserted into a page using an XHTML element. The attribute values as well as the body tell the action what to do and the data to use. An example of this is the <c:out> action. This is but one of a number of custom actions that form part of the JSTL core library. All of the JSTL libraries are implemented using the same mechanisms for the application-specific custom tag library.

How to Implement Custom Action

To use custom tags, you need to define three separate components:
  • The tag handler class defining the tag’s behaviour
  • The TLD file mapping the XML element names to the tag implementation
  • The JSP file in which the tag library is being used


Below we provide an overview of each of the relevant component as well as how to build the components using the different tag styles.

Using the Tag Handler Class to Define Tag Behaviour

When you create a new tag, the first thing you need to do is to define a Java class that informs the system what to do when it encounters this tag. All classes that are used as tags must extend SimpleTagSupport in order to implement the SimpleTag interface as well as leverage the standard implementations for many of the methods for the SimpleTag interface. The SimpleTag interface and the SimpleTagSupport class are located in the javax.servlet.jsp.tagext package.

When the web container loads your tag handling class, it instantiates it using a no argument constructor. If you don’t have this type of constructor, the instantiation will fail. If you fail to define a constructor in your class, the Java compiler will provide a no argument constructor for you automatically. The processing for the tag is located in the doTag method. This method is used to output content to the JSP page by invoking the print method of the JspWriter class. You obtain an instance of the JspWriter class by calling the getJspContext().getOut() method from inside the doTag method. The doTag method will be invoked at request time by the web container. The SimpleTag model never reuses tag handler instances. A new instance of the tag handler class will be created for every tag occurrence on your JSP page. This helps to avoid problems with race conditions and cached values even when you use instance variables in a tag handler class.

Once you have compiled the tag handler class, it is placed in the same location as a regular servlet (i.e. inside the WEB-INF/classes directory consistent with the package structure). Or you can archive it within a JAR file, and place the JAR file in the WEB-INF/lib directory of the web application. For example, the package for the tag handler class shown below is com.acme.mytestproj.tags package and its class name is MessageTag. This would provide the directory hierarch for the the MessageTag.class file under the WEB-INF/classes directory. The tag handler is shown below:

Java Code: MessageTag Custom Tag Handler
package com.acme.mytestproj.tags;
  
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import com.ora.jsp.beans.motd.*;

public class MessageTag extends SimpleTagSupport {
    private MessageBean mb = new MessageBean(  );
  
    // Attributes
    private String category;
  
    public void setCategory(String category) {
        this.category = category;
    }
  
    public void doTag(  ) throws IOException {
        mb.setCategory(category);
        JspWriter out = getJspContext().getOut(  );
        out.println(mb.getMessage(  ));
    }
}
For each attribute supported by the custom action, the tag handler must implement a bean-style setter method, such as the setCategory( ) method. The container calls methods defined by the SimpleTag interface, such as the doTag( ) method, to let the tag handler do any processing required.

The Tag Library Descriptor File

Once you have created your tag handler class, the next task is to declare this class to the server and associate it with a particular XML tag name. In order to accomplish this we create a TLD file in XML format. This file has certain fixed information concerning the XML Schema instance declaration, a short name and description that you decide for the library and a series of tag descriptions. An example of a TLD file is shown below:

XML Code: Example of TLD File
<?xml version="1.0" encoding="UTF-8" ?> 
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
   http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0">
   <tlib-version>1.0</tlib-version> 
   <short-name>acmjsp-taglib</short-name> 
   <tag>
      <description>JSP Message tag</description> 
      <name>example</name> 
      <tag-class>com.acme.mytestproj.tag.MessageTag</tag-class> 
      <body-content>tag-dependent</body-content>
   </tag>
</taglib>
Below is a short description of the contents of the TLD file in their required order for defining the custom tag.
description - this optional element allows the tag developer to document the purpose of the custom tag.
name - this required element defines the name of the tag as it will be referred to by the JSP page (really tag suffix, as will be seen shortly).
tag-class- this element is required in order to provide the fully qualified name of the tag handler class that implements the tag.
body-content - this is a required element that indicates to the web container how to treat the content between the beginning and ending occurrence of the tag, if it exists. This value can be either empty, scriptless, tag-dependent, or a JSP.
As you can see there are a number of values that can be returned by the body-context. We will look at each one.
Body content is empty - there is no content that is allowed to appear in the body of the tag. In this case, the declared tag can only appear in the following manner:

XML Code: Syntax for Custom Action Tags with Body
<prefix:tag/>
or
<prefix:tag></prefix:tag>
There must be no spaces between the opening and closing tags. If you place any content inside the tag body it will generate a page translation error.
Body-Content is scriptless - this means that the tag body is permitted to have JSP content except for any scripting elements like <% ... %> or <%= ... %>. If there are scripting elements in the tag body, it will be processed just like any other JSP content.
Body-content is tag-dependent - this means that the tag is allowed to have any type of content as its body. The developer of the tag handler to must get access to the content and process it. An example of this would be developing a custom tag allowing the JSP page designer to execute a SQL statement by providing the SQL in the tag’s body. In this case you would use tag-dependent as the value of the body-content element.
Body-content is JSP - this value is provided for backward compatibility with the classic custom tag model. It is not considered a legal value when it is used with the SimpleTag API. Under the SimpleTag API model, there is no legal way of allowing scripting elements to appear as the tag body.

Once you have created our TLD file, you need to place it inside the WEB-INF directory or under a subdirectory consistent with the package name.

Using a Custom Tag Library in a JSP 1.1 Container

Before JSP 1.2, web containers did not automatically locate custom tag libraries. Instead you needed to tell the web container exactly where to find the TLD. There are a number of approaches that you can use. For example, you could specify a symbolic name as the uri attribute value in combination with defining the mapping from the symbolic name to the library location in the deployment descriptor for the application. An example of this is shown below:

XML Code: Example of Deployment Descriptor for Custom Tag
<web-app>
  ...
  <taglib>
    <taglib-uri>
      atltaglib
    </taglib-uri>
    <taglib-location>
      /WEB-INF/lib/alttaglib_2_0.jar
    </taglib-location>
  </taglib>
  ...
</web-app>
In the listing above, the symbolic name is shown in the<taglib-uri> element, and the path to the tag library JAR file or TLD file is shown in the <taglib-location> element. The web container will determine if the uri matches the symbolic name in the web.xml. If it doesn’t match the web container will assume it’s the file path:

XML Code: Example of Taglib Directive in JSP
<%@ taglib prefix="atl" uri="/WEB-INF/lib/atltaglib_2_0.jar" %>
If the path starts with a slash,it is viewed as a context-relative path, otherwise it is viewed as a JSP-page-relative path. The file can be either the TLD file itself or a JAR file that includes the TLD file as META-INF/taglib.tld.

The JSP File

You now have the implementation of your tag handler and you have created a TLD and place the compiled tag handler implementation and the TLD in the proper directory. You are now ready to create a JSP page that will use the tag. The first thing that you need to add at the top of your tag is the taglib directive. It has the following form:

XML Code: Syntax of Taglib Directive
<%@ taglib uri="..." prefix="..." %>
In the taglib directive, there are two key pieces of information. They are explained below.
The uri is a required attribute. It can be either an absolute or relative URL that refer to the target TLD file. An example would be a simple URL relative to the Web application’s root directory. Doing this you can have multiple JSP pages in different that refer to the same TLD file from multiple JSP pages in different directories. As the TLD file is placed underneath the WEB-INF directory, even though URL refers to the directory since it is resolved on the server and not the client, it is always protected from direct client access.
The prefix is a required attribute. It specifies a prefix to be used before any tag name that is defined in the taglib declaration. If, for example, we had defined in the TLD file a tag called mytag and used in the taglib directive a prefix attribute, acm, when you wanted to use the custom tag in the JSP page, you would need to refer to the tag by acm:mytag. You would define the tag either with or without a body as shown below:
with a body:

XML Code: Example of Custom Tag Action with Body
<acm:mytag>Arbitrary JSP</acm:mytag>
without a body:

XML Code: Example of Custom Tag Action without Body
<acm:mytag  />
The example JSP file is shown below:

XML Code: Example of JSP Page Custom Tag Action
<%@ page contentType="text/html" %>
<%@ taglib prefix="atl" uri="/WEB-INF/tlds/atltaglib.tld" %>
<html>
  <head>
    <title>Messages of the Day</title>
  </head>
  <body bgcolor="blue">
    <h1>Messages of the Day</h1>
    <h2>Words to Live By!</h2>
    <i>
      <atl:motd category="thoughts" />
    </i>
  
    <h2>Quotes to Remember</h2>
    <i>
      <atl:motd category="quotes" />
    </i>
  </body>
</html>
There are two things that web container needs to accomplish to use the actions from the tag library are to recognize that an element represents a custom action from a specific library, and to locate the Java class or tag file that implements the custom action logic.

The first requirement is to determine to which library an action belongs. This requirement is satisfied by the taglib directive's prefix attribute. All the elements in the JSP page using the declared prefix are considered to be part of the custom tag library. Custom tag libraries will define a default prefix. This is used in the library's documentation or in page-authoring tools that can insert custom action elements in a page. But you have the option to use any prefix that you would like except those that are reserved by the JSP specification.

The second requirement is to locate the tag file or Java class implementing the custom action logic. It is the uri attribute that satisfies the second requirement. The uri attribute holds the string used by the web container to locate the TLD for the custom tag library. This is where the web container can find the Java class or tag file names for all of the actions in the library. In JSP Specification 1.2 or later, the web container uses the default URI for the library as it is included in the TLD and should also be part of the documentation for the library. In the graphic shown below showing the relation between the JSP page and the TLD file it is shown as atltaglib.

Tutorial:Review of JSP Tag Libraries for the Web Component Developer Exam-a22-jsppagerelation.jpg
Figure: JSP Page Relation to TLD File

Once a web application is started, the web container scans the WEB-INF directory structure for all files TLD files (i.e files with .tld extensions) and all JAR files with files with .tld extensions in their META-INF directory. For each TLD that the web container finds, the web container locates the default URI from the TLD. It then creates a map between the URI and the TLD that contains it. The JSP page then uses the taglib directive with a uri attribute value that matches the default URI.

For every custom tag library, the default URI common convention is to use an HTTP URL based around your organization, such as http://acme.com/atltags. This ensures that in almost all cases that the URI for the custom tag library would be unique. The URL doesn't need to refer to an existing resource. It only serves an identifier and the URL is not used by the web container to access the custom tag library over the Internet.

Now once the URI and the prefix for the custom tag library are defined, the web container is able to find the custom action implementation. The web container does this by first finding an element with a matching prefix. This is used to access the uri attribute value to locate the TLD. Next within the TLD, the mapping between the action element name and the class or tag file implementation is found to execute the action.

Editing JSP Pages with an XML Editor

All JSP action elements follow the XML notation. A XML-syntax aware editor facilitates the implementation of standard HTML and XHTML elements for your web application. The only issue is that JSP directive elements don’t comply with XML syntax. A web container will recognize the JSP elements along with XML/HTML comments. This is contrasts with an XML editor where it ignores comments. The workaround is to place the JSP directives within comment delimiters. This is shown in the example below:


XML Code: Example of Workaround for JSP Directives
<!--
<%@ page contentType="text/html" %>
<%@ taglib prefix="atl" uri="/WEB-INF/tlds/atltaglib.tld" %>
-->
<html>
  <head>
    <title>Messages of the Day</title>
    ...
Setting Action Attribute Values

Action attributes allow you to pass information to the tag. The general form for action attributes is:

XML Code: Syntax for Custom Tag Attributes
<prefix:name attribute1="value1" attribute2="value2"... />
They add significant flexibility to your tag library since attributes allow you to pass information to the tag. Let’s look at how to add attribute support to your tags.

Tag Attributes: Tag Handler Class

It is a straightforward process to add support for attributes. If you have an attribute called attribute1 that is part of your class that extends SimpleTagSupport or implements the SimpleTag interface then you provide a setter for that method in order to add attribute support. In the case of an attribute called attribute1, this would look like the following:

Java Code: Example of Setter for Custom Tag Attribute
public void setAttribute1(String value1) { 
   doSomethingWith(value1);
}
The attribute name must always start with a letter in lowercase. In terms of the setter that would correspond to the first letter of the attribute name being in upper case. This is shown in the figure below:
Tutorial:Review of JSP Tag Libraries for the Web Component Developer Exam-a22-attributeandsetter.jpg
Figure: Relationship between Attribute and Setter Method

General attribute handlers are used to store the attribute in a filed for use by the doTag method. This is shown in the following listing where a new value is stored for the method attribute:

Java Code: Example of Setter for Custom Tag Attribute
private String message = "Default Value"; 
...
public void setMessage(String message) {
   this.message = message;
}
If the tag handler is accessed from external classes, you should provide a getter method in addition to the setter method for the attribute. Only the setter method is required for the attribute to be considered an action attribute. An example of a tag with both getter and setter methods are shown below:
Tutorial:Review of JSP Tag Libraries for the Web Component Developer Exam-a22-attributesaccessors.jpg
Figure: Tag with Accessors for the Attribute

Tag Attributes: Tag Library Descriptor

All tag attributes should be declared inside the tag element by use of an attribute element. The attribute element has three nested elements appearing between <attribute> and </attribute>. These elements are the following:
  • name - this is a required element defining the case-sensitive attribute name.
  • required - this optional element stipulates that the attribute must always be supplied, true, or that it is optional, false (default). If it is not required (i.e. false) and the attribute is omitted in the JSP page, no call will be made to the setAttributeName method. In this case, you need to supply default values to the attributes that are not required in the tag. If the attribute is required in the tag but is omitted in the JSP page, it will result in an error at page translation time.
  • rtexprvalue - this optional element indicates whether an attribute value can be either a JSP scripting expression (i.e. <%= expression %>) or JSP EL (i.e. ${bean.value}), or whether it must be a fixed string. In the case of allowing for expressions that are determine at request time, then rtexprvalue must be true. Note that this is different for the tag body which is not allowed to have JSP scripting expressions.


Tag Attributes: JSP File

The JSP page has to declare the tag library using the taglib directive in the following form:

XML Code: Syntax for Taglib Directive
<%@ taglib uri="..." prefix="..." %>
In the case of attribute names, the usage of the tag is very similar with the addition of being able to specify a custom attributes. Attribute names are case-sensitive and so they need to appear in the JSP page exactly as they were declared inside the TLD file. Since all custom tags are based on XML syntax, you need to enclose the value of an attribute in either single or double quotes. An example of this is shown below:

XML Code: Syntax for Tag Action Attribute
<some-prefix:tag1 attribute1="value" />
Example of Actions from a Tag Library

In the custom tag we defined earlier, MessageTag we have create an attribute named, category which allows us to add a message from a specified category to the JSP page. The table showing the attribute of our custom tag is shown below:

Tutorial:Review of JSP Tag Libraries for the Web Component Developer Exam-a22-messagetagattributes.jpg
Table: MessageTag Attributes

In the case of our custom tag, MessageTag, the category attribute value for the <atl:mod> action has the value String in the "Java type" column. String is the Java type for a text value. Action attributes can be of any Java type. If we decided to include another attribute for the <atl:mod> action for setting the number of messages to return, we would most likely make this attribute an int type. The web container will treat attribute values in the same manner as bean properties and automatically convert text values to numeric or Boolean values using the same conversion methods that allow for the attribute to be set as a text value. A Java programmer can also link the custom action to a property editor to convert text values to more complex data structures.

The category attribute may also accept an EL expression as well as a static text value as indicated in the "Dynamic Value Accepted" column of the above table. So an EL expression would evaluated for each page request. This would allow you to provide an attribute value that differs between invocations. This is what is meant in the the . It indicates if the attribute can be set by an EL expression. Support for EL expressions isn't necessary for all custom or even standard action attributes, but typically all attributes except those named var and scope accept an EL expression value. This is a convention established by the JSTL specification. For any custom tag libraries that you develop, you should always provide information about whether an attribute accepts dynamic value as part of the tag library documentation. Next we show again the use of the custom tag and the category attribute in a JSP page below:

XML Code: Example of JSP Page
<%@ page contentType="text/html" %>
<%@ taglib prefix="atl" uri="/WEB-INF/tlds/atltaglib.tld" %>
  
<html>
  <head>
    <title>Messages of the Day</title>
  </head>
  <body bgcolor="blue">
    <h1>Messages of the Day</h1>
    <h2>Words to Live By!</h2>
    <i>
      <atl:mod category="thoughts" />
    </i>
  
    <h2>Quotes to Remember</h2>
    <i>
      <atl:mod category="quotes" />
    </i>
  </body>
</html>
Key things of note is the use of the <atl:mod> element name prefix that matches the prefix we defined for the custom tag library via the taglib directive. There is no difference between the syntax for a custom action action element and the syntax for standard actions. There is an opening tag, optionally attributes and a body, and finally a closing tag. If there is no body used then there is just one tag ending with />. All JSP action elements including Standard actions, JSTL actions as well as custom actions are used in exactly the same way. In the first occurrence of our custom action we set the category attribute to “thoughts” and then is the second occurrence we set it to “quotes”. The <atl:mod> action adds a message from the specified category to the page, resulting in the response shown in the listing above.

The JSP Standard Tag Library

For the convenience of developers, there is a standard library of custom tags known as the JSP Standard Tag Library (JSTL). The JSTL libraries are implemented based on the same mechanisms as an application-specific custom tag library. JSTL provides many tag libraries for a number of generic aspects of an application. It had been universally excepted by the Java community and because of that it became its own specification. Although the JSTL specification is not part of the JSP specification but it’s closely related it and you are required to know about the JSTL core tag library required for the web component developer exam. JSTL actually consists of five different tag libraries. This is to minimize name collisions among the actions in different categories. In the table below, we provide the default URIs and recommended prefixes for all JSTL libraries:

Tutorial:Review of JSP Tag Libraries for the Web Component Developer Exam-a22-jstllibraries.jpg
Table: JSTL 1.1 Libraries

The URIs that are used for JSTL 1.1 are due to backward compatibility with JSTL 1.0 applications deployed in a JSP 2.0 container. This is due to EL expressions being evaluated by the container instead of the tag handlers starting with JSP 2.0. The first four libraries cover core functionality for things like iteration, conditional processing and expression language support, XML processing for parsing and XSL transformation, I18N formatting for local language formatting and parsing and database for accessing a database via JSPs. The last custom tag library around functions contains a set of functions that can be invoked in an EL expression. A list of these functions are shown below:
Tutorial:Review of JSP Tag Libraries for the Web Component Developer Exam-a22-jstlfunctions.jpg
Table: JSTL Functions

As some web containers don’t provide native support for JSTL. If that is the case, you will need to install the JSTL Reference Implementation (RI) developed by the Apache Taglibs open source project as a library named Standard. The Apache Foundation’s Jakarta Taglibs project provides a very popular implementation of JSTL. To import JSTL into a Web application, follow these steps:
Download JSTL. Get the latest version of the Standard library from the Jakarta Taglibs project instead: Apache Taglibs - Apache Taglibs.
Unzip it to a directory. The directory can be any directory on your hard drive. Because Apache implementation ships with some supporting material (e.g., a sample Web application), we don’t need to copy all of it into our Web app.
Copy standard.jar and jstl.jar into the WEB-INF/lib of your application.
Import the library into your JSP page with the taglib directive. This uses the same taglib directive mechanism as in the following:


XML Code: Taglib Directive for JSTL Core Library
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
The JSTL Reference Implementation JAR files are listed in the table below:

Tutorial:Review of JSP Tag Libraries for the Web Component Developer Exam-a22-jstlreferimpl.jpg
Table: JSTL Reference Implementation JAR Files

To use a JSTL library in your JSP pages, just declare the library you need and use the actions just as any other custom action:

XML Code: Example of JSP Page with Custom Action
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
  <head>
    <title>Math JSP</title>
  </head>
  <body bgcolor="blue">
  
    <h1>Calculation</h1>
  
    12 + 21 + 30 = <c:out value="${12 + 21 + 30}" />
  
  </body>
</html>
Using Beans or Custom Actions

If you have created a bean and named it by using the <jsp:useBean> action. You can then access the bean's property values with another JSP standard action, named <jsp:getProperty>. This action will obtain the current value of a bean property and inserts it into the response body. An example of the <jsp:useBean> and <jsp:getProperty> action use with the MessageBean is shown below:

XML Code: Example of Use of JSTL Standard Tags
<jsp:useBean id="msg" 
  class="com.acme.mytestproj.tags.MessageBean" />
...
<jsp:setProperty name="msg" property="category"
  value="thoughts" />
...
<jsp:getProperty name="msg" property="message" />
You can do this using custom action to accomplish the same thing:
XML Code: Example of Custom Action Element
<atm:mod category="thoughts" />
Custom actions are able to use beans as input and output. You can use a custom action to save bean properties in a database or access information from a database and output it as part of page as a bean. Other beans not only carry information but encapsulate functionality intended for use in a number of different environments like servlets or JSP pages.

OK. That’s it. In the next article, we will custom in depth custom tag libraries.