Expert Spring MVC and Web Flow

(Dana P.) #1

// true!
assertEquals("Anya", bean.getNames().iterator().next().getFirstName());
// true!
assertEquals("Lala", bean.getNames().iterator().next().getLastName());
}


The preceding unit test passes, as we have chosen a LinkedHashSetas the Setimplementa-
tion and we’re setting properties of objects inside of the Set. However, the following unit test,
Listing 6-21, fails. Notice how we’re attempting to set the value of a Stringdirectly in the Set.


Listing 6-21.NestedSetCommandBean Unit Test (Fails)


public void testBindToStrings() {
// just like /servlet?strings[0]=Anya
request.addParameter("strings[0]", "Anya");


binder.bind(request); // errors at this point
}


■NoteThe DataBindersupports setting properties directly on individual objects, or objects in arrays,
Lists,Sets, or Maps only. It only supports setting objects directly, or objects in Lists, arrays, or Maps.


Up to this point, we have covered using the DataBinderto set properties of objects
directly, or within collections. However, all of the examples have used properties of type
String. The DataBindersupports more than simple Stringproperties through its use of
PropertyEditors. It’s possible to set properties of nearly any type, including primitives.


Non-String Properties


We’ve shown you a few examples of PropertyEditors before, normally connected with bean
definitions and the ApplicationContext. The same facilities apply here with the DataBinder.
For a quick review, a PropertyEditor’s job is to convert between a Stringvalue and a strongly
typed object, and back again. For instance, a UrlPropertyEditorwould convert the String
http://www.example.comto a java.net.URLclass with the value of http://www.example.com,
and from a java.net.URLobject back to a String.
Out of the box, the DataBinder, and its BeanWrapper, supports many different PropertyEditors.
This means your command beans can use a wide variety of property types, and the DataBinder
and its facilities will handle all of the conversion for you.
Table 6-1 lists the default PropertyEditors that come registered to the DataBinderby
default. If you require a type not covered in Table 6-1, it is very easy to create and register your
own PropertyEditors.


CHAPTER 6 ■THE CONTROLLER MENAGERIE 135
Free download pdf