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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Creating a Custom Converter<br />

As explained in “Conversion Model” on page 302, if the standard converters included with<br />

<strong>Java</strong>Server Faces technology don’t perform the data conversion that you need, you can easily<br />

create a custom converter to perform this specialized conversion.<br />

All custom converters must implement the Converter interface. This implementation, at a<br />

minimum, must define how to convert data both ways between the two views of the data<br />

described in “Conversion Model” on page 302.<br />

This section explains how to implement the Converter interface to perform a custom data<br />

conversion. To make this implementation available to the application, the application architect<br />

registers it with the application, as explained in “Registering a Custom Converter” on page 448.<br />

To use the implementation, the page author must register it on a component, as explained in<br />

“Registering a Custom Converter” on page 448.<br />

<strong>The</strong> Duke’s Bookstore application uses a custom Converter implementation, called<br />

tut-install/javaeetutorial5/examples/web/bookstore6/src/java/com/sun/bookstore6/converte<br />

to convert the data entered in the Credit Card Number field on the bookcashier.jsp page. It<br />

strips blanks and hyphens from the text string and formats it so that a blank space separates<br />

every four characters.<br />

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

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

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

from CreditCardConverter:<br />

public Object getAsObject(FacesContext context,<br />

UIComponent component, String newValue)<br />

throws ConverterException {<br />

String convertedValue = null;<br />

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

return newValue;<br />

}<br />

// Since this is only a String to String conversion,<br />

// this conversion does not throw ConverterException.<br />

convertedValue = newValue.trim();<br />

if ( (convertedValue.contains("-")) ||<br />

(convertedValue.contains(" "))) {<br />

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

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

for(inti=0;i

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

Saved successfully!

Ooh no, something went wrong!