Friday, 19 April 2013

JSF 2 Custom Converter Example


JSF 2 Converter


In JSF we can create custom converter class which can give our own definition for data conversion.
Following steps required to create Converters
  1. Create a Java Converter class which implements javax.faces.convert.FacesConverter interface
  2. Override converter methods
  3. Apply converter annotations to Converter class
  4. Add converter tag for JSF input component

Create a converter class

package com.vinod.jsf;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
public class InputConverter implements Converter{

    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        System.out.println(" object value " + value);
        return value;

    public String getAsString(FacesContext context, UIComponent component, Object value) {
        System.out.println(" string value " + value);
        return "Mr." + value.toString();


Create a Managed bean

package com.vinod.jsf;

import javax.faces.bean.ManagedBean;

public class ConverterBean {
    public ConverterBean() {
    private String name;
    public String getName() {
        return name;
    public void setName(String name) { = name;
    public String submit() {
        System.out.println("submit clicked");
        return "ConverterExample.xhtml";

Create a JSF xhtml page

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns=""
<title>My JSF Examples</title>
            <h:form id="vinod">
                <h:outputText value="Converter Example"/>
                <h:inputText id="nametext" value="#{}">
                    <f:converter converterId="com.vinod.InputConverter" />
            <h:commandButton value="Click" id="cmd" action="#{converterBean.submit}" >

Run it..


Done…Download source code..