background image

Private Objects

<< Cooperating Tags | Tag Handler Examples >>
<< Cooperating Tags | Tag Handler Examples >>

Private Objects

To access an object created by an enclosing tag, a tag handler must first obtain its enclosing tag
by using the static method SimpleTagSupport.findAncestorWithClass(from,class) or the
SimpleTagSupport.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 privately named
objects would have to be managed by the tag handler; one approach would be to use a Map to
store name-object pairs.
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 connectionId attribute has been
set, the handler retrieves the connection object from the page context. Otherwise, the tag
handler first retrieves the tag handler for the enclosing tag and then retrieves the connection
object from that handler.
public class QueryTag extends SimpleTagSupport {
public int doTag() throws JspException {
String cid = getConnectionId();
Connection connection;
if (cid != null) {
// there is a connection id, use it
connection =(Connection)pageContext.
getAttribute(cid);
} else {
ConnectionTag ancestorTag =
(ConnectionTag)findAncestorWithClass(this,
ConnectionTag.class);
if (ancestorTag == null) {
throw new JspTagException(
"A query without
a connection attribute must be nested
within a connection tag.
");
}
connection = ancestorTag.getConnection();
...
}
}
}
The query tag implemented by this tag handler can be used in either of the following ways:
<tt:connection cid=
"con01" ... >
...
</tt:connection>
<tt:query id=
"balances" connectionId="con01">
SELECT account, balance FROM acct_table
where customer_number = ?
Programming Simple Tag Handlers
The Java EE 5 Tutorial · September 2007
264