Expert Spring MVC and Web Flow

(Dana P.) #1
CustomDateEditor firstDateEditor = new CustomDateEditor(firstDateFormat, true);
CustomDateEditor secondDateEditor = new CustomDateEditor(secondDateFormat, true);

binder.registerCustomEditor(Date.class, "firstDate", firstDateEditor);
binder.registerCustomEditor(Date.class, "secondDate", secondDateEditor);

request.addParameter("firstDate", "2001-01-01");
request.addParameter("secondDate", "01-01-2001");

binder.bind(request);

assertEquals(firstExpected, bean.getFirstDate()); // true!
assertEquals(secondExpected, bean.getSecondDate()); // true!
}

As you can see in Listing 6-30, when we register the PropertyEditorto the DataBinder, we
can also specify which property, or field, the PropertyEditorshould apply to. This overrides
any PropertyEditoralready bound to a class.

Custom PropertyEditors
Although Spring provides many useful PropertyEditors, often times you will wish to convert
some String value to a specific domain class from your object model. Creating and registering
your own PropertyEditors is as simple as registering any PropertyEditorto the DataBinder.
For example, consider a typical PhoneNumberclass. This class might encapsulate a typical
phone number, consisting of an area code and the number. The HTML form might allow a
phone number to be entered with a single text input field, as long as it conforms to the stan-
dard (xxx) xxx-xxxxformat.
To begin, let us define a simple PhoneNumberclass in Listing 6-31.

Listing 6-31.PhoneNumber Class

public class PhoneNumber {

private String areaCode;
private String prefix;
private String suffix;

public String getAreaCode() {
return areaCode;
}
public void setAreaCode(String areaCode) {
this.areaCode = areaCode;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {

142 CHAPTER 6 ■THE CONTROLLER MENAGERIE

Free download pdf