JSP allows you to create your own custom JSP tags. The JSP taglib directive allows you specify these custom tags in your JSP page and use them.
Syntax of taglib Directive
<%@ taglib uri = "uri of tag library(tld) file" prefix = "unique custom tag name" %>
uri is the location of your Tag Description Library(.tld) file.
prefix is any unique name of your choice which is used to refer to your custom tag.
taglib Directive Example
We are going to create a custom tag class by extending SimpleTagSupport class and store this file in WEB-INF directory of Apache-Tomcat,
i.e. "C:\apache-tomcat-9.0.2\webapps\ROOT\WEB-INF".
Tag1.java
//Creating a custom tag by extending SimpleTagSupport class.
package myCustomTag;
import java.io.*;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class Tag1 extends SimpleTagSupport
{
public void doTag() throws JspException, IOException
{
//Calling getJspContext() method of SimpleTagSupport class to retreive JspContext object.
JspContext jspCon = getJspContext();
//Using JspContext objext to call its method getOut() to retreive JspWriter object.
JspWriter out = jspCon.getOut();
//Using JspWriter object to print a message from Custom Tag to the web page.
out.println("Greetings from Custom Tag!");
}
}
How to compile Tag1.java
In order to compile the custom tag file - Tag1.java, make sure you've added the path to jsp-api.jar file(found in C:\apache-tomcat-9.0.2\lib) to the classpath of your System Variables.
Make sure the compiled file of Tag1.java i.e. Tag1.class, should be stored in WEB-INF/class directory, by entering the following command at command prompt from within WEB-INF directory -
Next, we are going to create a Tag Library Descriptor(TLD) File with .tld extension and this file should be stored in
C:\apache-tomcat-9.0.2\webapps\ROOT\WEB-INF, i.e. if you unpacked your Apache-Tomcat binary file in C: Drive.
Next we have created a JSP web page that that uses taglib directive to call the custom tag named BlueSky (which we have created) and
prints its message on the current web page.
TaglibExample.jsp
<html>
<head>
<title>Displaying Custom Tag using taglib directive</title>
</head>
<%@ taglib uri ="WEB-INF/CustomTag.tld" prefix="MyTag" %>>
<body>
<MyTag:BlueSky/>
</body>
</html>
As you may see in the JSP page above -
We have given prefix the name - "MyTag" and
uri is given the value of location of tag library(tld) file i.e. "WEB-INF/CustomTag.tld"
executing this JSP page includes the content of our custom tag BlueSky which we created Tag1.java and configured it in CustomTag.tld file to display
its message to a JSP web page.