Jsp custom tags example

Custom tags:

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

Advantages of custom tags:

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

How to use custom tag?

A custom tag may have zero or n attributes.

How to create a custom tag?

Steps to create a custom tag:
  1. 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. 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 of the custom tag.
               2. : Fully qualified name of the tag handler class.
  1. 3. JSP page: This is normal JSP page where we use created custom tag.


import java.io.IOException;
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 javatutorialpoint
public class CustomTag extends SimpleTagSupport{
 public void doTag() throws JspException, IOException {
      JspWriter out = getJspContext().getOut();
      out.println("This is our first custom tag.");
  <short-name>Our first custom tag</short-name>
<%@ taglib prefix="ftag" uri="WEB-INF/firsttag.tld"%>
  <title>custom tag example</title>


No comments: