Skip to main content

JSF Tip #47 - Package a custom converter

Posted by mriem on November 26, 2013 at 5:17 PM PST

Just like a composite component you might want to distribute a converter, but how would you package it? Easy, read the rest down below!

The 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 faces-config.xml

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

<faces-config version="2.1"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd">
</faces-config>

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/packageCustomConverter/)

And that is it.

Enjoy!

Related Topics >>