background image

Converting a Component's Value

<< Using the Standard Converters | Using DateTimeConverter >>
<< Using the Standard Converters | Using DateTimeConverter >>

Converting a Component's Value

Converting a Component's Value
To use a particular converter to convert a component's value, you need to register the converter
onto the component. You can register any of the standard converters on a component in one of
four ways:
Nest one of the standard converter tags inside the component's tag. These tags are
convertDateTime
and convertNumber and are described in
"Using DateTimeConverter"
on page 356
and
"Using NumberConverter" on page 357
, respectively.
Bind the value of the component to a backing bean property of the same type as the
converter.
Refer to the converter from the component tag's converter attribute.
Nest a converter tag inside of the component tag and use either the converter tag's
converterId
attribute or its binding attribute to refer to the converter.
As an example of the second approach, if you want a component's data to be converted to an
Integer
, you can simply bind the component's value to a property similar to this:
Integer age = 0;
public Integer getAge(){ return age;}
public void setAge(Integer age) {this.age = age;}
If the component is not bound to a bean property, you can employ the third technique by using
the converter attribute on the component tag:
<h:inputText
converter=
"javax.faces.convert.IntegerConverter" />
This example shows the converter attribute referring to the fully-qualified class name of the
converter. The converter attribute can also take the ID of the component. If the converter is a
custom converter, the ID is defined in the application configuration resource file (see
"Application Configuration Resource File" on page 437
).
The data corresponding to this example inputText tag will be converted to a
java.lang.Integer
. Notice that the Integer type is already a supported type of the
NumberConverter
. If you don't need to specify any formatting instructions using the
convertNumber
tag attributes, and if one of the other converters will suffice, you can simply
reference that converter using the component tag's converter attribute.
Finally, you can nest a converter tag within the component tag and use either the converter
tag's converterId attribute or its binding attribute to reference the converter.
The converterId attribute must reference the converter's ID. Again, if the converter is a custom
converter, the value of converterID must match the ID in the application configuration
resource file; otherwise it must match the ID as defined in the converter class. Here is an
example:
Using the Standard Converters
Chapter 11 · Using JavaServer Faces Technology in JSP Pages
355