The JSP container may create many instances of the tag handler but guarantees that an instance services only one request at a time. A JSP container also typically reuses a tag handler instance and so instance variables should be appropriately reset if necessary.
This example implements a tag handler for the simplest type of tag - - one without attributes or a body. This custom tag simply prints the current time and day.
package com.mycompany;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
// This tag simply emits the current date and time.
public class MyTagHandler extends TagSupport {
public int doStartTag() throws JspException {
try {
// Print the current date and time
pageContext.getOut().print(""+new java.util.Date());
} catch (java.io.IOException e) {
throw new JspTagException("MyTag: "+e.getMessage());
}
return SKIP_BODY;
}
public int doEndTag() {
return EVAL_PAGE;
}
}
A web application wishing to use the custom tag must not only include the custom tag's class file but also its Tag Library Descriptor (TLD) as well. The TLD is a file that contains information about one or more custom tags and is needed by a JSP container to process pages that use a custom tag. Here's the TLD file (mytaglib.tld) for the custom tag:
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<%-- Version of this tag library; it should have the form 123 or 123.456 --%>
<%-- The required version of JSP for this tag library --%>
<%-- The preferred prefix for this tag library --%>
<%-- This is the URI that uniquely identifies this tag library.
The URI does not have to exist; it is merely an identifier --%>
<%-- This name is used by tools to represent this tag library --%>
<%-- Name of tag in this library --%>
<%-- Specify that the tag must not have a body --%>
This is a description of the tag.
Here's an example of a JSP page that uses the custom tag. The TLD file is assumed to be in WEB-INF/tld and the MyTagHandler.class file in WEB-INF/classes/com/mycompany:
<%@ taglib uri="/WEB-INF/tld/mytaglib.tld" prefix="my" %>
No comments:
Post a Comment