Wiki

Clone wiki

Oracle JSF Expert 1Z0-896 / Custom converters

Converter interface

javax.faces.convert.Converter

public interface Converter {
    Object getAsObject(FacesContext context, UIComponent component, String value);

    String getAsString(FacesContext context, UIComponent component, Object value)  
}

Implementing the converter interface using @FacesConverter

@FacesConverter("userConverter")
public class UserConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String newValue) {
            if (somethingHasGoneWrong) {
                FacesMessage msg = new FacesMessage("Conversion error!", "Something went wrong");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ConverterException(msg);
            }
            return new User(newValue);
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object user) {
        return ((User) user).getFirstName();
    }

}

<h:outputText value="#{userBean.user}">
    <f:converter converterId="userConverter" />
</h:outputText>
or

<h:outputText value="#{userBean.user}" converter="userConverter" />

Implementing the converter interface using faces-config.xml

public class UserConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String newValue) {
            if (somethingHasGoneWrong) {
                FacesMessage msg = new FacesMessage("Conversion error!", "Something went wrong");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ConverterException(msg);
            }
            return new User(newValue);
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object user) {
        return ((User) user).getFirstName();
    }

}
<converter>
    <description>
        Converter for User
         numbers that normalizes
         the input to a standard format
    </description>
    <!--  if applied instead of converter-id then it applies to ALL User instances
    <converter-for-class>com.example.User</converter-for-class> -->
    <converter-id>userConverter</converter-id>
    <converter-class>
        com.example.UserConverter
    </converter-class>
</converter>

<h:outputText value="#{userBean.user}">
    <f:converter converterId="userConverter" />
</h:outputText>
or

<h:outputText value="#{userBean.user}" converter="userConverter" />

Override message coming from converter

<h:outputText value="#{userBean.user}" converter="userConverter" converterMessage="Something went REALLY wrong!" />

NB: faces-config.xml overrides any @FacesConverter

Updated