Binding Converters to a Managed Beans property
This tutorials shows you how to bind a number converter with a property from a managed bean. JSF converters, listeners and validator tags allow binding attributes. With this attribute you can bind a converter implementations to your managed bean properties.
Binding Converter with a managed beans property
In this example we bind a standard numberConverter
converter to a backing bean property. The advantages are
- Allowing the managed bean to instantiate and manage the implementation
- The managed bean can programatically access and change the implementation attributes
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Binding converters to Managed Bean</title>
</h:head>
<h:body>
<h2>JSF 2: Binding converters to Managed Bean</h2>
<h:outputText value="Amount: "/>
<h:outputText value="#{numbersBean.amount}">
<f:convertNumber binding="#{numbersBean.numberConverter}"/>
</h:outputText>
</h:body>
</html>
Managing the converter in the managed bean
Next we must define a NumberConverter
converter in our managed bean. We can alter the converter’s property programatically and change for example the type and the currency symbol.
package com.memorynotfound.jsf;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.convert.NumberConverter;
import java.util.Date;
@ManagedBean
@RequestScoped
public class NumbersBean {
private double amount = 13.24;
private NumberConverter numberConverter;
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public NumberConverter getNumberConverter() {
return numberConverter;
}
public void setNumberConverter(NumberConverter numberConverter) {
numberConverter.setType("currency");
numberConverter.setCurrencySymbol("€");
this.numberConverter = numberConverter;
}
}
Demo
URL: http://localhost:8080/jsf-binding-converter/