Custom Tag is a user-defined JSP language element. When it is contained in JSP page and it will translate into a servlet, the custom tag is converted to opertions on an object called a tag handler. The web container then invokes those operations when the JSP page’s servlet is executed.
If we want to create a custom tag, what we need to do is simply extend SimpleTagSupport class and override the doTag() method, where you can place your code to generate content for the tag.
Let’s getting started to create a custom tag now. As you can see below, consider we want to create two tag, one is user tag with name and isMale attribute, another is system tag with size attribute.
Above two class just override the doTag() method and take the current JspContext object using getJspContext() method, and then send message content to the current JspWriter object.
Secondly we need to create tld extention file. It’s a tag library file. let us see the codes.
<taglib> <tlib-version>1.0</tlib-version> <jsp-version>2.0</jsp-version> <short-name>custom tld</short-name> <tag> <name>user</name> <tag-class>com.jsp.custom.tag.UserTag</tag-class> <body-content>tagdependent</body-content> <attribute> <name>name</name> <required>true</required> <description>user name</description> <!-- the type default is String if it is not specified --> <!--<type>java.lang.String</type>--> </attribute> <attribute> <name>isMale</name> <required>false</required> <description>the use is male or not male</description> <type>java.lang.Boolean</type> </attribute> <attribute> <name>birthday</name> <type>java.util.Date</type> </attribute> </tag> <tag> <name>system</name> <tag-class>com.jsp.custom.tag.SystemTag</tag-class> <body-content>empty</body-content> <attribute> <name>size</name> <required>false</required> <description>the size of system</description> </attribute> </tag> </taglib>
Finally, we can use these both tags in our JSP page.