A Custom tag is a user defined JSP language element. When a JSP page containing custom tag is translated into a Servlet, the tag is converted to operations on an object called tag handler. The Web container then invokes those operations when the JSP page’s servlet is executed. It speeds up web application development because of code reuse feasibility. Custom tags can access all the objects available in JSP pages. Custom tags can modify the response generated by the calling page. Custom tags can be nested.
Custom tag library consists of one or more Java classes called Tag Handlers and an XML tag library descriptor file (tag library).
A class which has to be a tag handler needs to implement Tag interface or IterationTag interface or BodyTag interface or it can also extend TagSupport class or BodyTagSupport class. All the classes that support custom tags are present inside a package called javax.servlet.jsp.tagext.
Let us create a custom tag which will does substring operation on given input. For this we will first create our Tag Handler class. Create a class called SubstrTagHandler and copy/paste following code in it.
In above code we have created three attributes: input, start and end. These are the inputs that we will get when the custom tag will be invoked from a JSP file. Also note that, these attributes have getter and setter methods which will be used to set the property values.
Now we will create the tag descriptor file also called TLD. Create a file called SubstrDescriptor.tld in WEB-INF directory of your web project and copy / paste following content in it.
<?xml version="1.0" encoding="UTF-8"?><taglib><tlibversion>1.0</tlibversion><jspversion>1.1</jspversion><shortname>substr</shortname><info>Sample taglib for Substr operation</info><uri>https://www.viralpatel.net/jsp/taglib/substr</uri><tag><name>substring</name><tagclass>net.viralpatel.jsp.custom.taglib.SubstrTagHandler</tagclass><info>Substring function.</info><attribute><name>input</name><required>true</required></attribute><attribute><name>start</name><required>true</required></attribute><attribute><name>end</name><required>true</required></attribute></tag></taglib>
In above tld file, <tag> is used to define a custom tag. Each new tag will have its own tag handler class which we specify in <tagclass> tag. Also <name> tag in <tag> represents the tag name that we use in jsp file. We have provided the three attributes with this tag: input, start and end. input is the String whose sub string needs to be parsed. start is the start index and end is the end index.
We have just created our first Custom Taglib for JSP. Now let us use the custom taglib in a JSP file. For this create index.jsp in your web application (if it exists, modify it and add this code) and add following code in it. <required> true make these attribute mandatory.