Custom tags

Custom tags:

Custom tags are the user defined tags. These tags are mainly used for code re-usability.

Advantages of custom tags:

  1. Code re-usability.
  2. Scriptlet tags are not needed.

How to use custom tag?

<prefix:tagname attributeName=attributeValue />  

A custom tag may have zero or n attributes.

How to create a custom tag?

Steps to create a custom tag:

  1. Tag handler class: is used to write the action for the custom tag. Our tag handler class inherits the TagSupport class. Custom tag action will be written in the doStartTag() method of TagSupport class.
  2. TLD file: It refers to the Tag Library Descriptor file. This file contains the tag name, tag attributes and tag handler class. A TLD file should have .tld extension. It should be inside the WEB-INF directory.

             Commonly used attributes in TLD file:

               1. <name>: Name of the custom tag.

               2. <tag-class>: Fully qualified name of the tag handler class.

    3. JSP page: This is normal JSP page where we use created custom tag.


import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;

 * This class is used for defining a custom tag.
 * @author W3schools360
public class CustomTag extends SimpleTagSupport{
	public void doTag() throws JspException, IOException {
      JspWriter out = getJspContext().getOut();
      out.println("This is our first custom tag.");


	 Our first custom tag


<%@ taglib prefix="ftag" uri="WEB-INF/firsttag.tld"%>

		custom tag example




jsp example 67
Download this example.
Next Topic: Custom tag with attributes.
Previous Topic: JSTL fn:trim() function with example.