Please find the below answer, which prints the odd value using a custom tag.
1) Create the Tag handler class
To create the Tag Handler, we are inheriting the TagSupport class and overriding its method doStartTag().To write data for the jsp, we need to use the JspWriter class.
The PageContext class provides getOut() method that returns the instance of JspWriter class. TagSupport class provides instance of pageContext bydefault.
package com.test;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
public class CountTagHandler extends TagSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
public int doStartTag() throws JspException {
JspWriter out=pageContext.getOut();
try{
Integer attribute = (Integer)pageContext.getAttribute("numberOfVisits", PageContext.APPLICATION_SCOPE);
//Print the value only if it is even
if(attribute != null && attribute % 2 == 0) {
out.print(attribute);
}
}catch(Exception e){System.out.println(e);}
return SKIP_BODY;
}
}
2) Create the TLD file
Tag Library Descriptor (TLD) file contains information of tag and Tag Hander classes. It must be contained inside the WEB-INF directory.
File: mytags.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>http://tomcat.apache.org/example-taglib</uri>
<tag>
<name>count</name>
<tag-class>com.test.CountTagHandler</tag-class>
</tag>
</taglib>
3) Create the JSP file
Let's use the tag in our jsp file. Here, we are specifying the path of tld file directly. But it is recommended to use the uri name instead of full path of tld file. We will learn about uri later.
It uses taglib directive to use the tags defined in the tld file.
From the jsp or from anywhere else in the project, set the "numberOfVisits".
Eg:
jsp file1:
<%! static int count = 0; %>
<%
application.setAttribute("numberOfVisits", count++);
%>
<a href="second.jsp">Custom link</a>
This is the second jsp file:
<h3>Using tag</h3>
<%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>
Application count: <m:count/>
