Searching...
Friday, 19 April 2013

JSF 2 Custom Converter Example

12:49

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;
@FacesConverter("com.vinod.InputConverter")
public class InputConverter implements Converter{

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

    @Override
    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;

@ManagedBean
public class ConverterBean {
    public ConverterBean() {
    }
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.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"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core">
<head>
<title>My JSF Examples</title>
</head>
            <h:body>
            <h:form id="vinod">
                <h:outputText value="Converter Example"/>
                <h:inputText id="nametext" value="#{converterBean.name}">
                    <f:converter converterId="com.vinod.InputConverter" />
                </h:inputText>
            <h:commandButton value="Click" id="cmd" action="#{converterBean.submit}" >
            </h:commandButton>
        </h:form>
    </h:body>
</html>
  

Run it..

 

Done…Download source code..
https://github.com/kkvinodkumaran/myrepository

0 comments: