
The below recipe is just an example of what you can find in the JSF 2.0 Cookbook from Packt.JSF standard converter tags allow binding attributes (this is also true for listener and validator tags). This means that developers can bind converter implementations to backing bean properties. The main advantages of using the binding facility are:
- developer can allow to the backing bean to instantiate the implementation.
- the backing bean can programmatically access the implementation’s attributes.
How to do it...To successfully accomplish a binding task, you can follow three simple steps (these steps are true for converter, listener and validator tags):
1. Nest the converter (listener, validator) tag in the component tag.
2. Put in the backing bean a property that take and return the converter (listener, validator) implementation class.
3. Reference the backing bean property using a value expression from the binding attribute of the converter (listener, validator) tag. Per example, let’s bind the standard
convertNumber converter to a backing bean property. The idea is to let the backing bean to set the formatting pattern of the user's input. First, you have to register the converter onto the component by nesting the
convertNumber tag within the component tag. Then, you have to reference the property with the binding attribute of the
convertNumber tag.
<h:form id="numberFormID">
<h:inputText id="numberID" value="#{numbersBean.numbery}">
<f:convertNumber binding="#{numbersBean.number}" />
</h:inputText>
<h:message showSummary="true" showDetail="false" for="numberID"
style="color: red; text-decoration:overline"/>
<br />
<h:commandButton value="Submit" action="selected?faces-redirect=true"/>
</h:form>
The number property would look something like this:
package numbers;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.convert.NumberConverter;
@ManagedBean
@SessionScoped
public class NumbersBean {
private NumberConverter number;
private float numbery;
public float getNumbery(){
return this.numbery;
}
public void setNumbery(float numbery){
this.numbery=numbery;
}
public NumberConverter getNumber(){
return this.number;
}
public void setNumber(NumberConverter number){
number.setType("currency");
number.setCurrencySymbol("$");
this.number=number;
}
}
How it works...In our example, the backing bean sets the formatting pattern within the
convertNumber tag, which means that the user’s input will be constrained to this pattern. This time the numbers are formatted as currencies, without using specific attributes in
convertNumber tag. Instead of this we use the binding attribute to reference the number property, which is a
NumberConverter instance, offering us access to this class methods.
The above recipe is just an example of what you can find in the JSF 2.0 Cookbook from Packt.