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

Custom Converter Example

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 "hr_mi_se_Converter.java" 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.parseInt(hr_mi_se[1])*60+
  Integer.parseInt(hr_mi_se[2]);
 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;

    if(hours<10){
    str_hours="0"+hours;
    }
    if(minutes<10){
  str_minutes="0"+minutes;
  }
    if(seconds<10){
    str_seconds="0"+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"?>
<faces-config>
............
............
<converter>
<converter-id>hr_mi_se_Converter</converter-id>
<converter-class>hr_mi_se_Converter</converter-class>
</converter>
...........
...........
</faces-config>

 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="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>

<f:view>
 <html>
 <body>
 <h:form>
  <b>Please enter the time below :</b><br></br>
  <h:inputText id="input_text">
  <f:converter  converterId="hr_mi_se_Converter" />
  </h:inputText>
  
  &nbsp;&nbsp;&nbsp;"Hours<b>:</b>Minutes<b>:</b>Seconds"
    format. <b>(Ex. 01:05:50)</b></br>
  
  <h:message for="input_text" style="color:RED"/></br></br>
  <h:commandButton value="Submit"/>
 </h:form>
 </body>
 </html>
</f:view>

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.