10.12.2012 Views

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Programming SimpleTag Handlers<br />

256<br />

<strong>The</strong> following validate method checks whether the value of attr1 is a valid Boolean value.<br />

Note that because the value of attr1 can be computed at runtime, validate must check<br />

whether the tag user has chosen to provide a runtime value.<br />

public class TwaTEI extends TagExtraInfo {<br />

public ValidationMessage[] validate(TagData data) {<br />

Object o = data.getAttribute("attr1");<br />

if (o != null && o != TagData.REQUEST_TIME_VALUE) {<br />

if (((String)o).toLowerCase().equals("true") ||<br />

((String)o).toLowerCase().equals("false") )<br />

return null;<br />

else<br />

return new ValidationMessage(data.getId(),<br />

"Invalid boolean value.");<br />

}<br />

else<br />

return null;<br />

}<br />

}<br />

Setting Dynamic Attributes<br />

Simple tag handlers that support dynamic attributes must declare that they do so in the tag<br />

element of the TLD (see “Declaring Tag Handlers” on page 249). In addition, your tag handler<br />

must implement the setDynamicAttribute method of the DynamicAttributes interface. For<br />

each attribute specified in the tag invocation that does not have a corresponding attribute<br />

element in the TLD, the web container calls setDynamicAttribute, passing in the namespace of<br />

the attribute (or null if in the default namespace), the name of the attribute, and the value of the<br />

attribute. You must implement the setDynamicAttribute method to remember the names and<br />

values of the dynamic attributes so that they can be used later when doTag is executed. If the<br />

setDynamicAttribute method throws an exception, the doTag method is not invoked for the<br />

tag, and the exception must be treated in the same manner as if it came from an attribute setter<br />

method.<br />

<strong>The</strong> following implementation of setDynamicAttribute saves the attribute names and values<br />

in lists. <strong>The</strong>n, in the doTag method, the names and values are echoed to the response in an<br />

HTML list.<br />

private ArrayList keys = new ArrayList();<br />

private ArrayList values = new ArrayList();<br />

public void setDynamicAttribute(String uri,<br />

String localName, Object value ) throws JspException {<br />

keys.add( localName );<br />

values.add( value );<br />

}<br />

<strong>The</strong> <strong>Java</strong> <strong>EE</strong> 5<strong>Tutorial</strong> • June 2010

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!