JSF Converters

Published: Saturday, 13 November 2010

This is similar to a PropertyEditor. It helps convert between Strings (being sent by the browser) into useful objects. Here’s a sample converter:

public class CountryConverter implements Converter {

    // returns a Country object
    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String countryCode) {
        Country country = new Country();
        country.setCode(countryCode);
        return country;
    }

    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {
        if (o instanceof Country) {
            Country c = (Country) o;
            return c.getCode();
        }
        return "";
    }
}

The above code will convert between a String and a Country. The object class passed into getAsString should also be a Country if you have registered this correctly.