Online Training Spring Hibernate Training in Delhi R Programming Training Course Big Data and Hadoop Training Java Training

Custom Converter Example

This section explains creating custom converter. When the user inputs value to the component, it is simple string value. Now you may be in the need of using this value as a different object like Boolean, Date etc. Converters can help in this conversion. J


JSF Tutorials: Easy steps to learn JSF Java Server Faces (JSF) Tutorials What is JSF Mojarra? JSF Life Cycle JSF Examples JSF Tutorial For Beginners Roseindia JSF Tutorial JSF core Tag Reference JSF internationalization example Tomahawk selectOneCountry tag RCFaces About Hibernate, Spring and JSF Integration Tutorial Creating Login Page In JSF using NetBeans JSF Hello World Declaring the Bean class in the faces-config.xml file Creating a Web Application with the JSF Framework Binding the Form Elements With the Bean Properties Adding Navigation in JSF Application Binding Component Instance to a Bean Property Tomahawk validateEqual tag Tomahawk validateEmail tag Tomahawk validateCreditCard tag Tomahawk selectOneListbox tag Tomahawk selectManyListbox tag Tomahawk selectManyCheckbox tag Tomahawk selectBooleanCheckbox tag Tomahawk saveState tag Tomahawk popup tag Tomahawk inputCalendar tag Tomahawk htmlTag tag Tomahawk graphicImage tag Tomahawk documentHead tag Tomahawk documentBody tag Tomahawk document tag Tomahawk column tag DataBase Connectivity with MySql in Visual Web JSF Application Using Net Beans IDE Retrieve Image in JSF From MySQL Table Using NetBeans IDE JSF Training Java Sever Faces 1.2 - JSF 1.2 Display Data from Database in JSF Application Business Objects of Business Logic tier Setup MySQL Database Working with Database through JDBC Working with JavaScript & CSS Referencing a Localized Message Referencing Resource Bundle from a Page Binding Component Value to an Implicit Object Phase Listener Value Change Event Listener Action Event Listener

Custom Converter Example


This section explains creating custom converter. When the user inputs value to the component, it is simple string value. Now you may be in the need of using this value as a different object like Boolean, Date etc. Converters can help in this conversion. JSF framework has provided many converters like Boolean Converter, Byte Converter, Number Converter etc. These converters converts values into appropriate type of object and returns it also to the page in the appropriate format. JSF flexible architecture provides you freedom to create your own converters. These can be used to check the value in the correct format. For example, In our application user is provided an input box to fill time in "hours:minutes:seconds" format. This String is converted as Object by the converter and also converted back in String when it needs to display in the web-page. Now if the user doesn't fill time in correct format then it displays error message showing the conversion could not be successful.

To create custom converter you need to implement "Converter" interface of javax.faces.converter package in your class.

Steps to follow :

  1. Create a class that implements javax.faces.converter.Converter interface.
  2. Import necessary packages and classes.
  3. Implement two abstract classes "getAsObject()", "getAsString()" provided by Converter interface. getAsObject() method converts the String (User Input) to Object and getAsString() method converts the Object to String to send back to the page.
  4. Configure the configuration file (faces-config.xml) adding <converter> element. This element has child elements <converter-id> (name of the converter to be used while programming )and <converter-class> ( name of the converter class which we have created).
  5. Create view page where <f:converter> tag is used with attribute "converterId" which specifies the name of the converter which we have specified in <converter-id> element of <converter> element in "faces-config.xml" file.
  6. Use <h:message> tag to display the error message.

The steps above have been implemented in our application "customconverter". This will help you to understand the process of creating custom converter. Just go through the following steps :

Step1 : Create a class "hr_mi_se_Converter" that implements the Converter interface and implements two abstract methods "getAsObject()", "getAsString()". Save this file as "" in WEB-INF/classes directory of your application.

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.*;
import javax.faces.application.*;

public class hr_mi_se_Converter implements Converter {
  public hr_mi_se_Converter() {
  public Object getAsObject(FacesContext facesContext, 
  UIComponent uiComponent, 
  String param){
  try {
  String hr_mi_se[] = param.split(":");
  int seconds = 
  Integer.parseInt(hr_mi_se[0])*60*60 + 
 Integer sObject= new Integer(seconds);
   return sObject;
   catch (Exception exception) {
  throw new ConverterException(exception);
  public String getAsString(FacesContext facesContext, 
  UIComponent uiComponent, 
  Object obj) {
    try {
  int total_seconds = (int)((Integer)obj).intValue();
  int hours=(total_seconds)/(60*60); 
    int rem=(total_seconds)%(60*60); 
    int minutes=rem/60; 
    int seconds=rem%60; 
    String str_hours=""+hours; 
    String str_minutes=""+minutes;
    String str_seconds=""+seconds;

    return str_hours + ":" + str_minutes + ":" + str_seconds;
    catch (Exception exception) {
    throw new ConverterException(exception);

In this class "param" represents the string provided by the user in the component. This string is passed to the getAsObject() method. Now we can use this according to our requirement of manipulation and return the appropriate object. "obj" parameter passed in getAsString() method represents the converted object in the previous method. This method is called while displaying in the page. So return the appropriate String by manipulating this object. If there is any problem in this process we can handle it by try and catch block. An error message is shown to the current page if conversion is not successful.

Step2 : Configure the configuration file (faces-config.xml). Open this file and add the following code.

<?xml version="1.0"?>

 Here <converter-id> gives ID to the converter that will be used in our page and <converter-class> specifies the implementing class.

Step3 : Now we can code for the page "page.jsp" where <f:converter> tag is used to associate the converter to the component using converterId attribute. Value of this attribute is given the ID of the converter which we have specified in the configuration file. 

<%@ taglib uri="" prefix="f" %>
<%@ taglib uri="" prefix="h" %>

  <b>Please enter the time below :</b><br></br>
  <h:inputText id="input_text">
  <f:converter  converterId="hr_mi_se_Converter" />
    format. <b>(Ex. 01:05:50)</b></br>
  <h:message for="input_text" style="color:RED"/></br></br>
  <h:commandButton value="Submit"/>

Output : When user fills wrong input then it displays error message in the current page as it is shown below otherwise processes according to the logic of the application.


Share on Google+Share on Google+

Custom Converter Example

Posted on: February 26, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Custom Converter Example   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image