Skip to main content

JSF Tip #16 - Writing your own Converter

Posted by mriem on October 4, 2012 at 3:57 PM PDT

Writing you own converter is a pretty straight forward process. It really comes down to implementing the Converter API.

Say you want to write a converter that will convert colors. Lets assume we support, "Red", "Green" and "Blue".

  package color;

  public class ColorConverter implements Converter {

    public Object getAsObject(FacesContext context, UIComponent component, String value) {
      if ("Red".equals(value)) {
        return new Color(255, 0, 0);
      }
      if ("Green".equals(value)) {
        return new Color(0, 255, 0);
      }
      if ("Blue".equals(value)) {
        return new Color(0, 0, 255);
      }

      throw new ConverterException("Unable to convert color: " + value);
    }

    public String getAsString(FacesContext context, UIComponent component, Object value) {
      if (value instanceof Color) {
        Color color = (Color) value;

        if (Color.RED.equals(color)) {
          return "Red";
        }
        if (Color.GREEN.equals(color)) {
          return "Green";
        }
        if (Color.BLUE.equals(color)) {
          return "Blue";
        }
      }

      throw new ConverterException("Unable to convert to a color");
    }
  }

To make sure you can use your custom Converter you will need configure it so the JSF runtime knows about it. Adding it to your faces-config.xml will do the trick.

  <converter>
    <converter-id>ColorConverter</converter-id>
    <converter-class>color.ColorConverter</converter-class>
  </converter>

And hooking this converter up to a inputText would be done as follows.

  <h:inputText value="#{echo.color}">
    <f:converter converterId="ColorConverter"/>
  </h:inputText>