Custom Tags in JSP

Introduction to custom tags

  • Custom tags are the user defined tags.
  • Custom tags are distributed in a tag library which defines a set of related custom tags.
  • They are used to remove the complexity of the business logic and separate it from the JSP page.
  • It also provides the code reusability of the custom tag.


1. Create an empty tag:
<prefix:tagname attr1=value1....attrn=valuen />

2. Create a Custom tag:
<prefix:tagname attr1=value1....attrn=valuen>
body code  

Creating a Custom Tag

To create a custom tag we need three things.
i. Tag handler class
ii. Tag Library Descriptor (TDL) file
iii. Use the Custom tag in the JSP file.

Tag Handler Class

We can create a custom tag by implementing SimpleTag, Tag or BodyTag interface during the life cycle of the tag.

There is a getOut( ) method in pageContext class that returns the instance of JspWriter class. All the classes that support custom tag are present inside javax.servlet.jsp.tagext.

Example : Creating own custom tag


import java.util.Calendar;  
import javax.servlet.jsp.JspException;  
import javax.servlet.jsp.JspWriter;  
import javax.servlet.jsp.tagext.TagSupport;
public class TagHandlerDemo extends TagSupport
     public intdoInstantTag() throws JspException
         JspWriter out=pageContext.getOut();
             out.print("This is custom Tag");
         catch(Exception e)

Tag Library Descriptor

It is an XML document contained inside the WEB-INF directory. It has the information of tag and Tag Handler class. TDLs are used by the JSP web container to validate the tags.

The extension of Tag Library Descriptor must be .tdl.

Example : Creating own custom tag by using Tag Library handler


    <short-name>Custom Tag Demo</short-name>

Use the Custom tag in the JSP File

The taglib directive in JSP page must specify the path of the URI (Uniform Resource Identifier) field in TDL path.

It provides the taglib directive that is used to define in the tdl file.

Example :Creating own custom tag in JSP file


<%@ taglib prefix="mypre" uri="WEB-INF/msg.tld"%>
        <title>Custom Tags in JSP File</title>
     Current Date and Time: <m:today/>