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 :
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.
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.
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.
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.
Liked it! Share this Tutorial