Expert Spring MVC and Web Flow

(Dana P.) #1
Listing 6-27.DateCommandBean Unit Test

protected void setUp() throws Exception {
bean = new DateCommandBean();
request = new MockHttpServletRequest();
binder = new ServletRequestDataBinder(bean, "bean");
}

public void testBind() throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date expected = dateFormat.parse("2001-01-01");

CustomDateEditor dateEditor = new CustomDateEditor(dateFormat, true);
binder.registerCustomEditor(Date.class, dateEditor);

request.addParameter("date", "2001-01-01");

binder.bind(request);

assertEquals(expected, bean.getDate()); // true!
}

The registerCustomEditor(Class, PropertyEditor) (shown in Listing 6-27) configures
the DataBinderto use the PropertyEditorany time it encounters a property with the given
Class.
A second form, registerCustomEditor(Class, String, PropertyEditor), (not shown in
Listing 6-27) takes a third parameter, which is the full path name to a property. If you specify
the property name, the Classparameter can be null, but should be specified to ensure cor-
rectness. If the property name points to a collection, then PropertyEditoris applied to the
collection itself if the Classparameter is a collection, or to each element of the collection if
the Classparameter is not a collection.
Working with PropertyEditors not supported in the default set requires a bit more work,
but still results in a fairly simple setup. You will first create an instance of the CustomDateEditor
and provide it with your chosen DateFormatobject. The PropertyEditoris then registered with
the DataBinder, assigning it to a class it will be responsible for converting (in this case, the Date
class). After you register it, proceed as normal, and the CustomDateEditorwill handle any
property of type Date.
As you may guess, when you register a PropertyEditorwith the DataBinder, that
PropertyEditoris then used any time the Dateclass is encountered. While most times this
may be what you want, there are some situations where you may want two different date
formats for two different properties of the same object.
To handle this situation, you may register a PropertyEditorto be used for a specific
property, instead of for every instance of that class. Using this type of registration provides
very specific data binding on a per-property basis instead of the default per-class basis.
For example, we will create a command bean with two Dateproperties. One property we
will require the user to use the format YYYY-MM-DD, while the other property will require the for-
mat DD-MM-YYYY. We will create two CustomDateEditors, each with its own date parsing format.
Then, we will register each CustomDateEditorto their specific properties. Listing 6-28 contains
the new command bean with two Dates.

140 CHAPTER 6 ■THE CONTROLLER MENAGERIE

Free download pdf