background image

Programming Simple Tag Handlers

<< Defines an EL Variable | Tag Handlers for Basic Tags >>
<< Defines an EL Variable | Tag Handlers for Basic Tags >>

Programming Simple Tag Handlers

Programming Simple Tag Handlers
The classes and interfaces used to implement simple tag handlers are contained in the
javax.servlet.jsp.tagext
package. Simple tag handlers implement the
SimpleTag
interface.
Interfaces can be used to take an existing Java object and make it a tag handler. For most newly
created handlers, you would use the
SimpleTagSupport
classes as a base class.
The heart of a simple tag handler is a single method, doTag, which is invoked when the end
element of the tag is encountered. Note that the default implementation of the doTag method of
SimpleTagSupport
does nothing.
A tag handler has access to an API that allows it to communicate with the JSP page. The entry
point to the API is the JSP context object (
javax.servlet.jsp.JspContext
). The JspContext object
provides access to implicit objects. PageContext extends JspContext with servlet-specific
behavior. Through these objects, a tag handler can retrieve all the other implicit objects
(request, session, and application) that are accessible from a JSP page. If the tag is nested, a tag
handler also has access to the handler (called the parent) that is associated with the enclosing
tag.
Including Tag Handlers in Web Applications
Tag handlers can be made available to a web application in two basic ways. The classes
implementing the tag handlers can be stored in an unpacked form in the /WEB-INF/classes/
subdirectory of the web application. Alternatively, if the library is distributed as a JAR, it is
stored in the /WEB-INF/lib/ directory of the web application.
How Is a Simple Tag Handler Invoked?
The SimpleTag interface defines the basic protocol between a simple tag handler and a JSP
page's servlet. The JSP page's servlet invokes the setJspContext, setParent, and attribute
setting methods before calling doStartTag.
ATag t = new ATag();
t.setJSPContext(...);
t.setParent(...);
t.setAttribute1(value1);
t.setAttribute2(value2);
...
t.setJspBody(new JspFragment(...))
t.doTag();
The following sections describe the methods that you need to develop for each type of tag
introduced in
"Types of Tags" on page 229
.
Programming Simple Tag Handlers
The Java EE 5 Tutorial · September 2007
256