In this example, we are going to create a custom tag that prints the current date and time. We are performing action at the start of tag.

For creating any custom tag, we need to follow following steps:

  1. Create the Tag handler class and perform action at the start or at the end of the tag.
  2. Create the Tag Library Descriptor (TLD) file and define tags
  3. Create the JSP file that uses the Custom tag defined in the TLD file

Understanding flow of custom tag in jsp

1) Create the Tag handler class

To create the Tag Handler, we are inheriting the TagSupport class and overriding its method doStartTag().To write data for the jsp, we need to use the JspWriter class.

The PageContext class provides getOut() method that returns the instance of JspWriter class. TagSupport class provides instance of pageContext bydefault.

package com.javatpoint.sonoo;  
import java.util.Calendar;  
import javax.servlet.jsp.JspException;  
import javax.servlet.jsp.JspWriter;  
import javax.servlet.jsp.tagext.TagSupport;  
public class MyTagHandler extends TagSupport{  
public int doStartTag() throws JspException {  
    JspWriter out=pageContext.getOut();//returns the instance of JspWriter  
     out.print(Calendar.getInstance().getTime());//printing date and time using JspWriter  
    }catch(Exception e){System.out.println(e);}  
    return SKIP_BODY;//will not evaluate the body content of the tag  

2) Create the TLD file

Tag Library Descriptor (TLD) file contains information of tag and Tag Hander classes. It must be contained inside the WEB-INFdirectory.

File: mytags.tld

3) Create the JSP file

Let’s use the tag in our jsp file. Here, we are specifying the path of tld file directly. But it is recommended to use the uri name instead of full path of tld file. We will learn about uri later.

It uses taglib directive to use the tags defined in the tld file.

File: index.jsp
<%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>  
Current Date and Time is:


output of jsp custom tag example