Saturday, September 25, 2010

Standard Converters ...




Need for Conversion:


Converter is a hot topic in JSF as it makes the life of a developer easy. Let us assume that we have an input form where it accepts name, age and date of birth. The corresponding managed bean will have attributes having data types String, Integer and Date. But values are entered as String which needs to be converted to its appropriate type before the accessors accepts it.


Standard Converters:

These converters are already defined in JSF for most of the common conversion process. Some of them are as follows:


•javax.faces.Double
• javax.faces.Integer
• javax.faces.Float
• javax.faces.Boolean

Implementation of Standard Converters:


JSF Page:



<f:view>
<f:subview id="converter1">
<h:form>
<br/>
<br/>
<h:outputLabel value="Date Converter :"/>
<h:inputText id="text"
value="#{startPage.converterDate}"
onchange="submit()">
<f:convertDateTime pattern="yyyy/MM/dd" type="date"/>
</h:inputText>
<h:message for="text"/>
<br/>
</h:form>
</f:subview>
<f:subview id="converter2">
<h:form>
<br/>
<br/>
<h:outputLabel value="Integer Converter :"/>
<h:inputText id="text2"
value="#{startPage.converterAge}"
onchange="submit()"
converter="javax.faces.Integer"/>
<h:message for="text2"/>
<br/>
</h:form>
</f:subview>
<f:view>



Explanation:

The first converter enclosed within the <f:subview> tag intends to accept a String and converts it to a Date Object. The above objective is achieved by the <f:convertDateTime> tag which defines the format of the date with the help of pattern attribute and the type attribute conveys the model to receive a Date object.
The second converter enclosed within the <f:subview> tag accepts in String format and converts it to Integer using interface (javax.faces.Integer). The use of converter attribute accomplishes the task.


Managed Bean:




private Date converterDate;
private int converterAge;

public void setConverterDate(Date converterDate) {
System.out.println("Date Entered : "+converterDate);
this.converterDate = converterDate;
}
public Date getConverterDate() {
return converterDate;
}
public void setConverterAge(int converterAge) {
System.out.println("Age Entered : "+converterAge);
this.converterAge = converterAge;
}

public int getConverterAge() {
return converterAge;

}




Explanation:

The model represents two attributes i.e converterDate and converterAge with Date and Integer data type respectively. For verification purpose you can check by including a sys-out statement inside the setters as shown in the example.

Upcoming post will be basically targeting the “Custom Converter Implementation”. So stay tuned 'n' focused.

Cheers !!!

No comments:

Post a Comment