JSF Custom Converter Example in Eclipse

Introduction

In most of the scenario, JSF provided converters are sufficient. However, for application specific purposes, there may be a need to customize and convert the user entered string into some other data-type like phone no format. This can be done by using JSF Custom Converter.

Following steps are required to create Custom Converters in JSF.

Steps

  1. Create a converter class by implementing javax.faces.convert.Converter interface.
  2. Override both getAsObject() and getAsString() methods.
  3. Map the converter in faces-config.xml file
  4. Link your custom converter class to JSF component via f:converter tag.


In this example we are going to create a custom converter that formats an SSN by inserting ‘-‘ separators for UI display, and it will ommit the ‘-‘ separators when retrieving the SSN from UIInput component for server processing.

Introduction

In most of the scenario, JSF provided converters are sufficient. However, for application specific purposes, there may be a need to customize and convert the user entered string into some other data-type like phone no format. This can be done by using JSF Custom Converter.

Following steps are required to create Custom Converters in JSF.

Steps

  1. Create a converter class by implementing javax.faces.convert.Converter interface.
  2. Override both getAsObject() and getAsString() methods.
  3. Map the converter in faces-config.xml file
  4. Link your custom converter class to JSF component via f:converter tag.


In this example we are going to create a custom converter that formats an SSN by inserting ‘-‘ separators for UI display, and it will ommit the ‘-‘ separators when retrieving the SSN from UIInput component for server processing.


Directory structure of the project :




JSF Custom Converter


1 . Create Converter class :

Create a custom converter class by implementing javax.faces.convert.Converter interface and implement the methods getAsObject() and getAsString().

getAsObject() method converts the given string value into an Object and getAsString() method converts the given object into a String.


SSNConverter.java

package com.javawebtutor.jsf.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

public class SSNConverter implements Converter {
	public Object getAsObject(FacesContext facesContext, UIComponent component,
			String value) {
		if (value == null) {
			return null;
		}
		return value.replace("-", "");
	}

	public String getAsString(FacesContext facesContext, UIComponent component,
			Object value) {
		if (value == null) {
			return null;
		}
		String ssn = value.toString();
		if (ssn.length() == 9) {
			StringBuilder formattedSsn = new StringBuilder();
			String ssnPart1 = ssn.substring(0, 3);
			String ssnPart2 = ssn.substring(3, 5);
			String ssnPart3 = ssn.substring(5, 9);

			formattedSsn.append(ssnPart1);
			formattedSsn.append("-");
			formattedSsn.append(ssnPart2);
			formattedSsn.append("-");
			formattedSsn.append(ssnPart3);
			ssn = formattedSsn.toString();
		}
		return ssn;

	}

}

2 . Create Managed Bean :

SSNBean.java

package com.javawebtutor.jsf.bean;

public class SSNBean {
	private String ssn;

	public String getSsn() {
		return ssn;
	}

	public void setSsn(String ssn) {
		this.ssn = ssn;
	}

}

3 . Registering the Custom Converter :

To make the Custom Converter visible to JSF Application, we have to register the Converter class by making an entry in the Faces Configuration file. The following is the xml code snippet for the same.

<converter>
  <description>A Converter for SSN </description>
  <converter-id>ssnConverter</converter-id>
  <converter-class>com.javawebtutor.jsf.converter.SSNConverter</converter-class>
</converter>

Complete faces-config.xml file is given below.

faces-config.xml

<?xml version="1.0"?>
<faces-config 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_1_2.xsd"
	version="1.2">
	<navigation-rule>
		<from-view-id>/index.jsp</from-view-id>
		<navigation-case>
			<from-outcome>result</from-outcome>
			<to-view-id>/result.jsp</to-view-id>
		</navigation-case>
	</navigation-rule>

	<managed-bean>
		<managed-bean-name>ssnBean</managed-bean-name>
		<managed-bean-class>com.javawebtutor.jsf.bean.SSNBean</managed-bean-class>
		<managed-bean-scope>session</managed-bean-scope>
	</managed-bean>

	<converter>
		<description>A Converter for SSN </description>
		<converter-id>ssnConverter</converter-id>
		<converter-class>com.javawebtutor.jsf.converter.SSNConverter</converter-class>
	</converter>
</faces-config>
 


4 . Create JSF Pages

Link above custom converter to JSF component via converterId attribute in f:converter tag.

index.jsp

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<f:view>
	<html>
<head>
<title>Index Page</title>
</head>
<body bgcolor="silver">
	<h:form>
		<h1>Custom Converter Sample Application</h1>
		<h:panelGrid columns="3">
		
           Enter Your SSN :
                                
            <h:inputText id="ssn"
				value="#{ssnBean.ssn}" size="20" required="true" label="ssn">
				<f:converter converterId="ssnConverter" />
			</h:inputText>

			<h:message for="ssn" style="color:red" />

		</h:panelGrid>

		<h:commandButton value="Submit" action="result" />

	</h:form>
</body>
	</html>
</f:view>

result.jsp

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<f:view>
	<html>
<head>
<title>Result Page</title>
</head>
<body bgcolor="silver">
	<h1>Custom Converter Sample Application</h1>

	<h:panelGrid columns="2">
	SSN After Conversion
		<h:outputText id="ssnout" value="#{ssnBean.ssn}">
			<f:converter converterId="ssnConverter" />
		</h:outputText>
		<br>
        SSN from UIInput component  : 
       <h:outputText value="#{ssnBean.ssn}" />

	</h:panelGrid>
</body>
	</html>
</f:view>

5 . Create web.xml file :

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<servlet>
		<servlet-name>Faces Servlet</servlet-name>
		<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>/faces/*</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>faces/index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

Run the Application :


welcome page

JSF Custom Converter

SSN without "-"

Enter 9 digit SSN without "-" we will get below result.

JSF Custom Converter

SSN with "-"

Enter 9 digit SSN without "-" we will get below result.

JSF Custom Converter


You can download the source code of the example by clicking on the Download link below.

Source+lib (Developed in Eclipse) : Download




comments powered by Disqus