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.

Syntax

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

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

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

//TagHandlerDemo.java

package com.tutorialride.com;  
import java.util.Calendar;  
import java.io.*;
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();
         try
         {  
             out.print("This is custom Tag");
             out.print(Calendar.getInstance().getTime());
         }
         catch(Exception e)
         {
             System.out.println(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

//taglb.tdl

<taglib>
    <tlib-version>1.0</tlib-version>
    <jsp-version>2.0</jsp-version>
    <short-name>Custom Tag Demo</short-name>
    <uri>http://tomcat.apache.org/example-taglib</uri>
    <tag>
       <name>WelcomeMsg</name>
       <tag-class>tutorialride.com.Details</tag-class>
       <body-content>empty</body-content>
    </tag>
</taglib>

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

//welcome.jsp

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