Custom tags are user-defined JSP language elements that encapsulate recurring tasks. Custom tags are distributed in a tag library, which defines a set of related custom tags and contains the objects that implement the tags. Custom tags have a rich set of features. They can be customized via attributes passed from the calling page. They can pass variables back to the calling page, access all the objects available to JSP pages and communicate with each other. You can create and initialize a JavaBeans component, create a public EL variable that refers to that bean in one tag, and then use the bean in another tag. They can be nested within one another and communicate via private variables. JSP Standard Tag Library (JSTL) is a standard set of commonly used tag libraries that you may be interested to read.

Custom tags separate presentation from business logic in that page content is created by page designers while the business logic’s are captured in the form of custom tags.  Now custom tags is not just for business logic but it can encapsulate other relatively complex functionality such as complex display, iteration, formatting and so on.

Custom Tags vs. JavaBeans

  • Custom tags can manipulate JSP contents while beans cannot
  • Complex operations can be reduced to a significantly simpler form with custom tags than the beans
  • Custom tags require quite a bit of more work to set up than do beans

Custom Tag Architecture

Three things make up Custom Tag architecture.
  • Tag handler class
    • Defines tag’s behavior
  • Tag library descriptor (TLD)‏
    • Maps XML elements to tag handler class
  • JSP file
    • Uses tags

Steps for implementing custom tags

  1. Write tag handlers class that defines tag’s behavior
  2. Write Tag library descriptor (TLD) file that maps XML elements to tag handler class
  3. Write JSP pages that use tags
  4. Configure and deploy tag library along with JSP pages

1. Tag handler class

First, tag handler class.  Tag handler class implement Tag interface or Bodytag interface.  If you are writing your tag handler from scratch, you will typically extend utility classes, TagSupport or BodyTagSupport classes, which are implementation of the interfaces with some built-in set up functions.
  • Implements
    • javax.servlet.jsp.tagext.Tag  or
    • javax.servlet.jsp.tagext.Bodytag interface
  • Usually extends
    • javax.servlet.jsp.tagext.TagSupport or
    • javax.servlet.jsp.tagext.BodyTagSupport class
  • Located in the same directory as servlet class files
    • <jwsdp-install>/webapps/ROOT/WEB-INF/classes/<package-directory-structure>

Example: Tag Handler

package moreservlets.tags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
/** Very simple JSP tag that just inserts a string  ("Custom tag example...") into the output.
 *  The actual name of the tag is not defined here; that is given by the Tag Library
*    Descriptor(TLD)  file that is referenced by the taglib directive  in the JSP file.
 *  <P>
 *  Taken from More Servlets and JavaServer Pages
 *  from Prentice Hall and Sun Microsystems Press,
 *  &copy; 2002 Marty Hall; may be freely used or adapted.
public class ExampleTag extends TagSupport {
  public int doStartTag() {
    try {
      JspWriter out = pageContext.getOut();
      out.print("Custom tag example " +
    } catch(IOException ioe) {
      System.out.println("Error in ExampleTag: " + ioe);

2. Tag Library Descriptor (TLD)‏

TLD file is an XML file that describes each tag with tag name, information on how body content should be handled, information on attributes, and full path of tag handler class.

  • XML file that describes
    • tag name
    • bodycontent
    • attributes
    • tag handler class
  • Container knows which tag is associated with which tag handler class via this file
  • Located
    • Usually under WEB-INF directory
  • Location specified in JSP file
    • Via uri attribute of taglib directive

Example: TLD 

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
<!-- a tag library descriptor -->
    A tag library from More Servlets and JavaServer Pages,
    <info>Simplest example: inserts one line of output</info>
    <info>Outputs a random 50-digit prime.</info>

3. JSP page

To use a custom tag in a JSP page, you must:

  • Declare the tag library containing the tag before the usage of any custom tags from that tag library
  • Use custom tags using custom tag syntax in a JSP page

It is assumed that the tag library has been configured and deployed with individual Web application or globally for all Web applications running on the server.

4. Declaring a tag library

Include taglib directive before tags are used


<%@ taglib prefix="myprefix" uri="myuri" %>

prefix: identifies the tag library

uri: uniquely identifies the tag library descriptor (TLD) directly or indirectly

This is the SimpleExample.jsp page which uses the tags.  Here it declares the tag library it wants to use first through <% taglib .. %> directive.  The location of the TLD file is specified via uri attribute and the prefix is set to msajsp.  In this example, the TLD file, msajsp-taglib.tld file, resides under /WEB-INF directory.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<%@ taglib uri="/WEB-INF/msajsp-taglib.tld" prefix="msajsp" %>
<TITLE><msajsp:example /></TITLE>
<H1><msajsp:example /></H1>
<msajsp:example />


How does Custom Tags work?

When JSP page is loaded into the web container, the JSP translator translates the JSP page into the servlet code.  Now when the translator encounters the “taglib” directive, it knows where to find the TLD file via “uri” attribute.  As we know now, the TLD file describes the binding between an action (tag handler) and a tag.

Now tags in a JSP page results in the appropriate servlet code which contains the tag handler.


This above picture shows the Tag interface’s methods on the left side and how these methods are invoked in sequence by the container on the right side of the picture.

The Tag interface defines the basic protocol between a tag handler and a JSP page’s servlet. It defines the life cycle and the methods to be invoked when the start and end tags are encountered.


The JSP page’s servlet invokes the setPageContext, setParent, and attribute setting methods before calling doStartTag. The JSP page’s servlet also guarantees that release will be invoked on the tag handler before the end of the page.

Here is a typical tag handler method invocation sequence:

  1. ATag t = new ATag();
  2. t.setPageContext(…);
  3. t.setParent(…);
  4. t.setAttribute1(value1);
  5. t.setAttribute2(value2);
  6. t.doStartTag();
  7. t.doEndTag();
  8. t.release();

Introduction to JSP 2.0

The focus of JSP 2.0 is ease of use. Web-tier developers can be categorized into 3 groups – tag library developer who has be fluent in HTML, XML, and Java technology.  And then we have advanced page author who might not be a Java developer but should be familiar with HTML and XML.  Then there are basic page authors whose primary skillset is HTML.

JSP 1.2 targets the first 2 tier groups while JSP 2.0 lowers the bar so that the third tier group, basic page authors can design the JSP page based Web tier applications.

JSP 1.2 Syntax With Scriptlets

<%-- Output Shopping Cart --%>
 <%@ page import="com.acme.util.*" %>
 <%@ taglib prefix="util" uri="http://mytaglib" %>

         <util:getShoppingCart var="cart" />
         <%  for( int i = 0; i < cart.size(); i++ ) {
                 CartItem item=(CartItem)cart.get(i);
                 <td><%= item.getName() %></td>
                 <td><%= item.getPrice() %></td>
         <%  } %>

Above code shows a JSP page in which the logic of displaying lineitems of a shopping cart is written using the JSP 1.2 syntax with scriptlets.  And as you can see, the page is rather hard to build and read.  Now let’s see how this page can be simplified using JSP 2.0 syntax in the following code.

JSP 2.0 Syntax Without Scriptlets

<%-- Output Shopping Cart --%>
 <%@ taglib prefix="util" uri="http://mytaglib" %>
 <%@ taglib prefix="c"
            uri="" %>
         <util:getShoppingCart var="cart" />
             <c:forEach var="item" values="${cart}">

Above code shows JSP page which contains same display logic but using JSP 2.0 expression language syntax.  For example, the shopping cart object is represented as ${cart} while the name and price of each line item in the shopping cart is represented as ${} and ${item.price} respectively.

JSP 2.0 Improved XML Syntax

<!-- Output Shopping Cart -->
 <html   xmlns:util="http://mytaglib"
         <util:getShoppingCart var="cart" />
             <c:forEach var="item" values="${cart}">

This code shows the same JSP 2.0 based page but using XML syntax even for the directives.  One reason you might want to build your JSP page as XML document is to be able to use XML schema for validation and to allow XML tools to be used for building and manipulating the JSP page.

Expression Language

Expression language is based on “Simplest Possible Expression Language” from JSTL 1.0. It basically let you access the property values of a JavaBean in a simpler syntax.  For example, “price” property value of “item” object can be displayed by using ${item.price} syntax.   It also let you perform arithmetic operations, comparisons.  You can also access the implicit objects such as form input parameters from the HTML client.

Integrated Expression Language Example

Using scriptlets:
   <jsp:useBean id="foo" />
   <%= foo.getBar() %>

Equivalent, using an EL expression:


Example – Display Product


<%@ taglib prefix="c" uri="" %>
<%@ attribute name="normalPrice" fragment="true" %>
<%@ attribute name="onSale" fragment="true" %>
<%@ attribute name="anotherJSPFragment" fragment="true" %>
<%@ variable name-given="name" %>
<%@ variable name-given="price" %>
<%@ variable name-given="origPrice" %>
<%@ variable name-given="salePrice" %>
<table border="1">
  <tr> <td>
            <c:set var="name" value="Hand-held Color PDA"/>
            <c:set var="price" value="$298.86"/>
            <jsp:invoke fragment="normalPrice"/>
        </td> <td>
            <c:set var="name" value="4-Pack 150 Watt Light Bulbs"/>
            <c:set var="origPrice" value="$2.98"/>
            <c:set var="salePrice" value="$2.32"/>
            <jsp:invoke fragment="onSale"/>
        </td>..... </tr> </table>


<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>
<html> <body> <h2>Products</h2>
     <jsp:attribute name="normalPrice">
          Item: ${name}<br/> Price: ${price}
      <jsp:attribute name="onSale">
        Item: ${name}<br/>
             <font color="red"><strike>Was: ${origPrice}</strike></font><br/>
             <b>Now: ${salePrice}</b>
    <jsp:attribute name="anotherJSPFragment">
           This is the item: <font color="red"> ${name} </font><br/>
           <font color="blue"><strike>Was: ${origPrice}</strike></font><br/>
            <b>The price now is: ${salePrice}</b>
<h2>Products (Same tag, alternate style)</h2>
            <jsp:attribute name="normalPrice">
                <b>${name}</b> @ ${price} ea.
            <jsp:attribute name="onSale">
                <b>${name}</b> @ ${salePrice} ea. (was: ${origPrice})‏

Tagged with: JAVA

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.