×
☰ See All Chapters

JSF Converters

  • Conversion of user submitted data to the desired data types is the mandatory part any web enterprise application. Developer should implement the conversion code to convert all input forms. In servlet and JSP we always gets the input data in String format and we explicitly type cast the input data to required data.  

  • In JSF no data conversion is required for String, primitive types. So in JSF converters are built in for String, primitive types. 

jsf-converters-0
 

Conversion of values will happen during Apply Request Values. If conversion process succeeds, then the submitted values are updated in the Managed Bean. If conversion fails, then the form is redisplayed and the value in the managed bean would not be updated. If any conversion error message is specified then error message is displayed. Conversion error message is specified from converterMessage attribute of input element. Error message is displayed in place of <h:message> tag.

jsf-converters-1
 

When user enters value for userId, value will be automatically converted to int type and is stored in userId property of HelloBean. While converting the value if conversion fails then converterMessage that is "Please enter integer value" will be displayed. Conversion fails because when user enters non numeric value, when user enters double value(if value entered exceeds size of int), when user enters fraction value etc…

In JSF implicit conversion takes place only for primitive and string data types. Suppose, If you want entered salary in the format   ###.00, If we want some digit to be occurred particular number of times. For example integer value should have at least 3, 2 times like 13345, 435863, 83536, if you want integer value to be entered in some particular format, for example phone number should start with +91 etc., then we should use custom converters.

Along with implicit conversion JSF also provides below converters for numbers and Date time.

  1. <f:convertNumber> 

  2. <f:convertDateTime> 

For these built in converters target type (conversion type) will not depends on the data type of properties in ManagedBean, but depends on the attributes and values used in the tags. But after conversion to store data in properties of ManagedBean should have matching types. For example to convert the date to required format (dd-mm-yyyy) we use <f:convertDateTime>, but after conversion to store this value property in ManagedBean should have data type Date (java.util.Date)


All Chapters
Author