Following is an example for Custom Tags in JSP.
Following are the steps to be performed while working with custom tags.
- Create the Tag handler class.
- Create TLD file.
- Write JSP code that should use TLD file.
custom.jsp
[java]
<%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>
Current Date and Time is: <m:today/>
[/java]
Here
tagname will implement tag from taglib and the
prefix which is given in the taglib library.
mytags.tld
[xml]
<?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>today</name>
<tag-class>MyTagHandler.MyTagHandler</tag-class>
</tag>
</taglib>
[/xml]
web.xml
[xml]
?xml version="1.0" encoding="UTF-8"?
<web-app>
<welcome-file-list>
<welcome-file>custom.jsp</welcome-file>
</welcome-file-list>
</web-app>
[/xml]
Here page will be compiled from the
custom.jsp .
MyTagHandler.java
[java]
import java.util.Calendar;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class MyTagHandler extends TagSupport{
public int doStartTag() throws JspException {
JspWriter out=pageContext.getOut();//returns the instance of JspWriter
try{
out.print(Calendar.getInstance().getTime());//printing date and time using JspWriter
}catch(Exception e){System.out.println(e);}
return SKIP_BODY;//will not evaluate the body content of the tag
}
}
[/java]
SKIP_BODY is an optional returned value but this value must be returned by doStartTag() when you want to skip the body evaluation that is it must be returned when the TagLibraryDescriptor file contains the element empty, the value “empty” shows that there will always be an empty action. The
java.util.Calendar.getInstance() method gets a calendar using the specified time zone and specified locale.
Output