The Java EE 5 Tutorial

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:

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).

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:

<h:inputText value="#{LoginBean.Age}" />
    <f:converter converterId="Integer" />
</h:inputText>

Instead of using the converterId attribute, the converter tag can use the binding attribute. The binding attribute must resolve to a bean property that accepts and returns an appropriate Converter instance. See Binding Converters, Listeners, and Validators to Backing Bean Properties for more information.