JSF Tip #46 - Creating a custom converter

Sometimes you need to write a custom converter to converter the client side representation to an object instance and vice versa. What is needed to use a custom converter? See below.

A custom converter

    package customconverter;

    import javax.faces.component.UIComponent;
    import javax.faces.context.FacesContext;
    import javax.faces.convert.Converter;
    import javax.faces.convert.FacesConverter;

    @FacesConverter(value = "customConverterId")
    public class CustomConverter implements Converter {

        public Object getAsObject(FacesContext context, UIComponent component, String value) {
            return new Custom();

        public String getAsString(FacesContext context, UIComponent component, Object value) {
            return value.toString();

And the page using it

    <?xml version='1.0' encoding='UTF-8'?>

    <!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml"
            <title>Custom Converter - f:converter tag</title>
            <h2>Custom Converter - f:converter tag</h2>
                Below you will see a string that was generated using a custom converter
                named 'customConverterId'. See the sources for the source for this
            <h:outputText value="#{customConverterBean.custom}">
                <f:converter converterId="customConverterId"/>

Posted November 25, 2013