A Custom Tag is a user-defined JSP language element. When a JSP page containing a Custom Tag is translated into a servlet, the tag is converted to operations on an object called a tag handler. The web container then invokes those operations when executing the JSP page's servlet.
JSP tag extensions let you create new tags you can insert directly into a JavaServer Page just as you would the built-in tags. Custom Tags are distributed in a tag library, that defines a set of related Custom Tags and contains the objects that implement the tags. The object that implements a Custom Tag is called a tag handler.
Let's do a demo: Create a "<today>" tag using the following.
- To create a custom JSP tag, you must first create a Java class that acts as a tag handler. So let us create a MyTagHandler.java class file inside the user package and write the following code in that class.
The code above is simple, where the "doTag()" method just prints the current day and time.
- Right-click on "WEB-INF" then click on "Others" then under "web catagory" click on "Tag Library Descriptor" as in the following:
- Click on "Next", then for the TLD Name provide "MyTag" as in the following.
- Open the MyTag.tld file and enter the following code to create the Custom Tag.
- Now it's time to use the above defined Custom Tag "Hello" in our JSP program as follows. Open Index.jsp and provide a reference to the tag library by writing the following code.
<%@ taglib uri="WEB-INF/tlds/Mytags.tld" prefix="m" %>
The preceding image shows the complete code of index.jsp.
- Run your index.jsp page. If everything goes fine then you will get the following output.