background image

Creating a Custom Converter

<< Using FacesMessage to Create a Message | The getAsObject Method >>
<< Using FacesMessage to Create a Message | The getAsObject Method >>

Creating a Custom Converter

Creating a Custom Converter
As explained in
"Conversion Model" on page 304
, if the standard converters included with
JavaServer Faces technology don't perform the data conversion that you need, you can easily
create a custom converter to perform this specialized conversion.
All custom converters must implement the Converter interface. This implementation, at a
minimum, must define how to convert data both ways between the two views of the data
described in
"Conversion Model" on page 304
.
This section explains how to implement the Converter interface to perform a custom data
conversion. To make this implementation available to the application, the application architect
registers it with the application, as explained in
"Registering a Custom Converter" on page 451
.
To use the implementation, the page author must register it on a component, as explained in
"Registering a Custom Converter" on page 451
.
The Duke's Bookstore application uses a custom Converter implementation, called
tut-install/javaeetutorial5/examples/web/bookstore6/src/java/com/sun/bookstore6/converters/CreditCardCo
to convert the data entered in the Credit Card Number field on the bookcashier.jsp page. It
strips blanks and hyphens from the text string and formats it so that a blank space separates
every four characters.
To define how the data is converted from the presentation view to the model view, the
Converter
implementation must implement the getAsObject(FacesContext, UIComponent,
String)
method from the Converter interface. Here is the implementation of this method
from CreditCardConverter:
public Object getAsObject(FacesContext context,
UIComponent component, String newValue)
throws ConverterException {
String convertedValue = null;
if ( newValue == null ) {
return newValue;
}
// Since this is only a String to String conversion,
// this conversion does not throw ConverterException.
convertedValue = newValue.trim();
if ( (convertedValue.contains(
"-")) ||
(convertedValue.contains(
" "))) {
char[] input = convertedValue.toCharArray();
StringBuffer buffer = new StringBuffer(input.length);
for ( int i = 0; i < input.length; ++i ) {
if ( input[i] ==
'-' || input[i] == ' '
) {
continue;
} else {
Creating a Custom Converter
Chapter 12 · Developing with JavaServer Faces Technology
393