Skip to main content

JSF Tip #46 - Creating a custom converter

Posted by mriem on November 25, 2013 at 3:55 AM PST

Sometimes you need to write a custom converter to converter the client side representation to an object instance and vice versa. What is need 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 {

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

    @Override
    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"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:head>
        <title>Custom Converter - f:converter tag</title>
    </h:head>
    <h:body>
        <h2>Custom Converter - f:converter tag</h2>
        <p>
            Below you will see a string that was generated using a custom converter
            named 'customConverterId'. See the sources for the source for this
            converter.
        </p>
        <h:outputText value="#{customConverterBean.custom}">
            <f:converter converterId="customConverterId"/>
        </h:outputText>
    </h:body>
</html>

Note the code for this sample is available as part of the Glassfish samples (see the subversion repository at https://svn.java.net/svn/glassfish-samples~svn/trunk/ws/javaee7/jsf/customConverter/)

And that is it.

Enjoy!