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.

Example:

CustomTag.java

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 w3spoint
 */
public class CustomTag extends SimpleTagSupport{
	public void doTag() throws JspException, IOException {
      JspWriter out = getJspContext().getOut();
      out.println("This is our first custom tag.");
   }
}

firsttag.tld

<taglib>
	 <tlib-version>1.0</tlib-version>
	 <jsp-version>2.0</jsp-version>
	 <short-name>Our first custom tag</short-name>
 
	 <tag>
	    <name>firstTag</name>
	    <tag-class>com.w3spoint.customtags.CustomTag</tag-class>
	    <body-content>empty</body-content>
	 </tag>
</taglib>

test.jsp

<%@ taglib prefix="ftag" uri="WEB-INF/firsttag.tld"%>
 
<html>
	<head>
		<title>custom tag example</title>
	</head>
	<body>
		<ftag:firstTag/>
	</body>
</html>

web.xml

<web-app>
 
  <welcome-file-list>
          <welcome-file>test.jsp</welcome-file>
  </welcome-file-list>	
 
</web-app>

Output:

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

 

Please follow and like us:
Content Protection by DMCA.com