Converter tags in JSF

1) Introduction

Data entered by the Client Application is always interpreted in the form of Strings. Not this is always we wish to have. There will be times, where the user input like age, salary, date of Birth should be represented by Integer, Double and Date objects respectively. Technically, Data is converted into their appropriate types before being processed by the Application. This is where JSF Converters come into picture. JSF implementation already comes with a bunch of Pre-Built Converters for the conversion of string to int, float, boolean etc.
Let us see the various Core Tags in Converter Category. Three Tags are available in this category. They are,

  • Convert Number Tag
  • Convert Date Time Tag
  • Converter Tag

Following sections discuss in greater detail about the importance of these Tags.

2) Convert Number Tag

The Convert Number Tag as identified by <f:convertNumber> is used to convert numbers to different representations like currency, percentage etc. This Tag is included with a bunch of attributes for formatting the display information. Currency Code and Currency Symbol can be used to control the Currency Information Display, Numbered Formatting can be fine tuned using a number of attributed like Maximum/Minimum Integer or Fraction Digits. Pattern Based Display of Numbers is also possible with the help of ‘pattern’ attribute. Following is the syntax declaration of the Convert Number Tag.


<f:convertNumber  pattern = "patternFormat"  minIntegerDigits = "minDigits"
maxIntegerDigits = "maxDigits" minFractionDigits = "minDigits"
maxFractionDigits = "maxDigits" groupingUsed = "trueOrfalse"
integerOnly = "trueOrfalse" type = "numberOrCurrencyOrPercent"
currencyCode = "currencyCodeValue" currencySymbol = "currencySymbol"
locale = "locale">
</f:convertNumber>

Following sections provide some samples for formatting the number text using the Convert Number Tag.


<h:outputText value = "12345.544">
<f:convertNumber pattern = "#,###.00"/>
</h:outputText>

<h:outputText value = "10000"<
<f:convertNumber minFractionDigits = "2"/>
</h:outputText<

<h:outputText value = "760.50">
<f:convertNumber type = "currency"/>
</h:outputText>

3) Convert Date Time Tag

This Tag is used to Convert the String to a Date/Time object and to Display it in Different Formats. This Tag has a dedicated set of Attribute Values for formatting both Date and Time Values. Following is the syntax definition of <h:convertDateTime> Tag.


<f:convertDateTime dateStyle = "default|short|medium|long|full"
timeStyle = "default|short|medium|long|full"
pattern = "pattern" type = "time|date|both">
</f:convertDateTime>

Following sample shows how to display the Birth Date of an User in the Full Date Format.

<h:outputText value = "#{user.birthDate}">
<f:convertDateTime dateStyle = "full"/>
</h:outputText>

4) Converter Tag

Custom Converter Components can be Plugged-in easily into the JSF Framework. Situations may demand to use Custom Converter Components for many cases. Assume that we have modeled a class called Name which holds first name and the last name of a User. The value entered by the Client, which is in the form of a String has to be converted into a Name object before being set as a property in the registered Managed Bean. For such a situtation the usage of Converter Tags will solve the problem. Let us see the syntax definition of the Converter Tag.

<f:converter converterId = "ClassNameOfTheConverter"/>

The attribute ‘converterId’ represents the alias name given to the Converter Class. Let us look into a Sample Custom Converter Component.
Following is the Model for the Name Class. It has two properties namely fName and lName. It also has a simple logic that, when given a String object that represents a name, it tries to find the first and last name with ‘,’ as the delimiter, to store it in the fName and the lName properties. Also note that Namer class implements the java.io.Serializable interface.
Namer.java

 public class Namer {

private String fName;
 private String lName;

public Namer() {
 }

public Namer(String fullName) {
 int commaIndex = fullName.indexOf(",");
 if (commaIndex == -1){
 fName = fullName;
 lName = "";
 }else{
 fName = fullName.substring(0, commaIndex);
 lName = fullName.substring(commaIndex + 1, fullName.length());
 }
 }

public Namer(String fName, String lName){
 this.fName = fName;
 this.lName = lName;
 }

public String getFName() {
 return fName;
 }

public void setFName(String fName) {
 this.fName = fName;
 }

public String getLName() {
 return lName;
 }

public void setLName(String lName) {
 this.lName = lName;
 }

public String toString(){
 return "[FName = " + fName + ", LName = " + lName + "]";
 }
 }

Let us look into the Code for a Custom Converter Component.
NameConverter.java

 package myconverters;

import javax.faces.component.*;
 import javax.faces.context.*;
 import javax.faces.convert.*;

public class NameConverter implements Converter{

private Namer namer = null;
 public NameConverter() {
 }

public Object getAsObject(FacesContext ctx, UIComponent comp, String value) {
 if (namer == null){
 namer = new Namer(value);
 }
 return namer;
 }

public String getAsString(FacesContext ctx, UIComponent comp, Object value) {
 if (namer != null){
 return namer.getFName() + " " + namer.getLName();
 }
 return null;
 }
 }

The first thing to note about this class is that it extends the javax.faces.convert. Converter interface. There are two methods to be overridden, one is the Converter.getAsObject() and the other is Converter.getAsString(). Converter.getAsObject() method will be called during Applying the Client Request Values to the UI Components. In this phase, the Conversion of the String Object to the Name Object will take place and the returned Name object will be set to the Managed Bean. And during Response Render Phase, the method Converter.getAsString() will be called, in which case the form will be populated with the String value as returned by this method.
After creating the Custom Converter Component, it has to be registered with the Application, by making entries in the faces-config.xml file. Following is the Xml Code Snippet for that,
faces-config.xml

<web-app>
...
<converter>
<converter-id>NameConverter</converter-id>
<converter-class>myconverters.NameConverter</converter-class>
</converter>
...
</web-app>

After registering the Custom Converter Component, it can be referenced in the JSF UI Components whose String Values has to be converted into Name object by directly referring it with its Id.


<P>Enter Your Name (FirstName,LastName)

<h:inputText value = "#{UserBean.namer}" id = "nameTextField" required = "true">
<f:converter converterId = "NameConverter"/>
</h:input>

Javabeat has published many of the good articles related to Java Server Faces (JSF). This list will help you to learn the basic concepts on JSF and how to start using in your projects, please have a look on these articles when time permits. Don’t forget to leave your feedback on the comments section. This helps us to provide better content for you.

The above article would provide the higher level of understanding on each concept.  If you would like to know all the features in detail, please buy any of the JSF books listed in the book recommendations for Java Server Faces (JSF). Hope this helps you!!

If you would like to receive future mails on Java articles, please subscribe here.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*