Example Of JSP Custom Tag


In this example, we're going to create a custom tag that prints the present-day date and time. We are appearing motionless at the beginning of the tag.

For developing any custom tag, we want to follow the following steps:

Create the Tag handler class and carry out motion at the beginning or on the top of the tag.

Create the Tag Library Descriptor (TLD) document and outline tags

Create the JSP document that makes use of the Custom tag described withinside the TLD document.

Understanding Flow of Custom Tag in JSP


To produce the Tag Handler, we're inheriting the TagSupport elegance and overriding its approach doStartTag().To write facts for the jsp, we want to apply the JspWriter class.

The PageContext class offers getOut() approach that returns the example of JspWriter class. TagSupport class offers an example of pageContext by default.

File: MyTagHandler.java

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 accommodate information of tag and Tag Handler training. It must be carried inside the WEB-INF directory.

File: mytags.tld

DOCTYPE taglib  
        PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"  


3)Create the JSP File

Let's use the tag in our jsp report. Here, we're specifying the route of tld document directly. But it's far recommended to apply the uri identity rather than complete route of tld report. We will find out about uri later.

It makes use of taglib directive to apply the tags described withinside the tld report.

File: index.jsp

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

download this example