background image

CooperatingTags

<< Tag Handler Manipulates the Body | The BodyTagSupport Class >>
<< Tag Handler Manipulates the Body | The BodyTagSupport Class >>

CooperatingTags

public class QueryTag extends BodyTagSupport {
public int doAfterBody() throws JspTagException {
BodyContent bc = getBodyContent();
// get the bc as string
String query = bc.getString();
// clean up
bc.clearBody();
try {
Statement stmt = connection.createStatement();
result = stmt.executeQuery(query);
} catch (SQLException e) {
throw new JspTagException(
"QueryTag: " +
e.getMessage());
}
return SKIP_BODY;
}
}
release
Method
A tag handler should reset its state and release any private resources in the release method.
Cooperating Tags
Tags cooperate by sharing objects. JSP technology supports two styles of object sharing.
The first style requires that a shared object be named and stored in the page context (one of the
implicit objects accessible to JSP pages as well as tag handlers). To access objects created and
named by another tag, a tag handler uses the pageContext.getAttribute(name,scope)
method.
In the second style of object sharing, an object created by the enclosing tag handler of a group of
nested tags is available to all inner tag handlers. This form of object sharing has the advantage
that it uses a private namespace for the objects, thus reducing the potential for naming conflicts.
To access an object created by an enclosing tag, a tag handler must first obtain its enclosing tag
using the static method TagSupport.findAncestorWithClass(from,class) or the
TagSupport.getParent
method. The former method should be used when a specific nesting of
tag handlers cannot be guaranteed. After the ancestor has been retrieved, a tag handler can
access any statically or dynamically created objects. Statically created objects are members of
the parent. Private objects can also be created dynamically. Such objects can be stored in a tag
handler using the setValue method and can be retrieved using the getValue method.
The following example illustrates a tag handler that supports both the named approach and the
private object approach to sharing objects. In the example, the handler for a query tag checks
whether an attribute named connectionId has been set. If the connection attribute has been
Programming Tags That Accept Scripting Elements
The Java EE 5 Tutorial · September 2007
282