The getAsObject Method
The getAsObject Method
buffer.append(input[i]);
}
}
convertedValue = buffer.toString();
}
return convertedValue;
}
During the apply request values phase, when the components' decode methods are processed,
the JavaServer Faces implementation looks up the component's local value in the request and
calls the getAsObject method. When calling this method, the JavaServer Faces implementation
passes in the current FacesContext instance, the component whose data needs conversion, and
the local value as a String. The method then writes the local value to a character array, trims the
hyphens and blanks, adds the rest of the characters to a String, and returns the String.
To define how the data is converted from the model view to the presentation view, the
Converter
implementation must implement the getAsString(FacesContext, UIComponent,
Object)
method from the Converter interface. Here is the implementation of this method
from CreditCardConverter:
public String getAsString(FacesContext context,
UIComponent component, Object value)
throws ConverterException {
String inputVal = null;
if ( value == null ) {
return null;
}
// value must be of the type that can be cast to a String.
try {
inputVal = (String)value;
} catch (ClassCastException ce) {
FacesMessage errMsg = MessageFactory.getMessage(
CONVERSION_ERROR_MESSAGE_ID,
(new Object[] { value, inputVal }));
throw new ConverterException(errMsg.getSummary());
}
// insert spaces after every four characters for better
// readability if it doesn
't already exist.
char[] input = inputVal.toCharArray();
StringBuffer buffer = new StringBuffer(input.length + 3);
for ( int i = 0; i < input.length; ++i ) {
if ( (i % 4) == 0 && i != 0) {
if (input[i] !=
' ' || input[i] != '-'){
buffer.append(
" ");
// if there are any
"-"'s convert them to blanks.
} else if (input[i] ==
'-') {
buffer.append(
" ");
Creating a Custom Converter
The Java EE 5 Tutorial · September 2007
394