Custom tags are user defiend tag elements that provide the code reusability in jsp. we can resuse that tag every where in our web application.
there are following steps needed to create custom tag in jsp :
1. Define tag handler class. 2. Define tag library descriptor(TLD). 3.Make a entry of this TLD file in the Deployment Descriptor. 4.Reference the tag library.
5.Use the tag in jsp.
>> Tag Handler class provides the implemention for tag/tagBody and to
do this it extends TagSupport/BodyTagSupport class, that implements Tag interface.
tag handler class code to create a simple custom tag that has one name attribute.
package com.customtag; import java.io.*; import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.TagSupport;
public class CreateTag extends TagSupport {
protected String name;
public String getName() { return name;
}
public void setName(String name) { this.name = name;
}
/* doStartTag() method writes an String content using pageContext.getOut(), * this forms the output that will get written on jsp page. * this method is invoked by the JSP page implementation object
*/
public int doStartTag() throws JspException { try { JspWriter out = pageContext.getOut(); out.println(“Welcome! “+getName()); } catch (IOException ioe) { ioe.printStackTrace(); } return EVAL_BODY_INCLUDE;
}
public int doEndTag() throws JspException { return EVAL_PAGE; }
}
>> Create a tag library descriptor file with testtag_lib.tld name in WEB-INF\tlds folder
1.0 1.2 test testingTag com.customtag.CreateTag
empty
attribute> name true true
>> To reference a tag library in jsp we use taglib directive :
>> Code to use this custom tag within body tag in index.jsp :
Output of this jsp is— Welcome! Mindfire