JSP Custom Tag

JSP custom tag provides flexibility to programmers, to declare their own tag. Thus, a user-defined tag can be created through custom tags to perform various operations.

These custom tags behave as operations on tag handler when JSP page is translated into servlet. These operations are invoked by web container when servlet of JSP page is executed.

How to create Custom Tag?

These are the steps that you need to follow to create custom tag: -

  • Tag Handler class – Create a tag handler class with .java extension. This class is used to perform operations of custom tag.
  • JSP file – Create a JSP file and include a tag library in it.
  • TLD file – It is required to create tag library file (i.e. TLD file) in WEB-INF directory of your project. This file is represented by .tld extension.

It is required to add both external jars i.e. jsp-api.jar and servlet-api.jar in classpath of your project before deploying the application.

Example of JSP Custom Tag

In this example,

customTagHandler.java

package com.tutorialandexample;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
public class CustomTagHandler extends SimpleTagSupport {
public void doTag() throws JspException,IOException
{
JspWriter jw=getJspContext().getOut();
jw.println("<h2>JSP Custom Tag</h2>");
}
}

Here, javax.servlet.jsp.tagext.* package contains all the classes that support custom tags and the role of SimpleTagSupport is to provide methods through which JSPWriter object can be accessed.

index.jsp

<html>
<head>
<title>Tutorial and Example</title>
</head>
<body>
   <%@ taglib uri="WEB-INF/xyz.tld" prefix="m" %> 
<m:message/>
</body>
</html>

xyz.tld

<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>MyCustom</short-name>
<tag>
<name>message</name>
<tag-class>com.tutorialandexample.CustomTagHandler</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>

Here, the name of tag (message) is given within the <name> tag and the full name of class is given within the <tag-class> tag. The value “empty” given within <body-content> means it doesn’t contain any body.

Output

Note – We can also provide body and attribute within custom tags.