10.12.2012 Views

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Creating a Custom Converter<br />

392<br />

}<br />

}<br />

buffer.append(input[i]);<br />

}<br />

}<br />

convertedValue = buffer.toString();<br />

return convertedValue;<br />

During the apply request values phase, when the components’ decode methods are processed,<br />

the <strong>Java</strong>Server Faces implementation looks up the component’s local value in the request and<br />

calls the getAsObject method. When calling this method, the <strong>Java</strong>Server Faces implementation<br />

passes in the current FacesContext instance, the component whose data needs conversion, and<br />

the local value as a String. <strong>The</strong> method then writes the local value to a character array, trims the<br />

hyphens and blanks, adds the rest of the characters to a String, and returns the String.<br />

To define how the data is converted from the model view to the presentation view, the<br />

Converter implementation must implement the getAsString(FacesContext, UIComponent,<br />

Object) method from the Converter interface. Here is the implementation of this method<br />

from CreditCardConverter:<br />

public String getAsString(FacesContext context,<br />

UIComponent component, Object value)<br />

throws ConverterException {<br />

String inputVal = null;<br />

if ( value == null ) {<br />

return null;<br />

}<br />

// value must be of the type that can be cast to a String.<br />

try {<br />

inputVal = (String)value;<br />

} catch (ClassCastException ce) {<br />

FacesMessage errMsg = MessageFactory.getMessage(<br />

CONVERSION_ERROR_MESSAGE_ID,<br />

(new Object[] { value, inputVal }));<br />

throw new ConverterException(errMsg.getSummary());<br />

}<br />

// insert spaces after every four characters for better<br />

// readability if it doesn’t already exist.<br />

char[] input = inputVal.toCharArray();<br />

StringBuffer buffer = new StringBuffer(input.length + 3);<br />

for(inti=0;i

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!