Expert Spring MVC and Web Flow

(Dana P.) #1

public void testSimpleBind() {
// just like /servlet?names['nickname'].firstName=Anya \
// &names['nickname'].lastName=Lala
request.addParameter("names['nickname'].firstName", "Anya");
request.addParameter("names['nickname'].lastName", "Lala");


binder.bind(request);

// true!
assertEquals("Anya", bean.getNames().get("nickname").getFirstName());

// true!
assertEquals("Lala", bean.getNames().get("nickname").getLastName());
}


The DataBindercan only refer to objects in a Mapwith keys of type String. This shouldn’t
be a concern, as the keys are HTTP request properties, which themselves are Strings.


Binding to Sets


Binding to properties of objects in Sets is possible, but is not as exact as working with Lists or
arrays. Sets in Java are unordered collections of unique objects, so referring to a single object
within the Setis not possible directly through the Setinterface. Spring’s DataBinderworks
around this limitation by iterating through the Setto find the object indicated by the index
specified. Obviously, which object resolves to the index is dependent on the Setimplementa-
tion. If you will be using Sets with the DataBinder, you should use a LinkedHashSetor some
other implementation that has a predictable iteration order.


■CautionWe strongly recommend against using Sets inside JavaBeans that will be used as command
objects. There is simply no way to replace or set a value into a Set,which severely limits its usefulness in
this context.


In contrast, the DataBinderis not able to set the value of objects in a Set. While the
DataBinderis able to iterate through the Setto locate an object whose properties need to be
set, there is no way to set a particular object directly into a Setat some location. The following
two examples, illustrated in Listings 6-20 and 6-21, shows what is and isn’t possible when
working with Sets and the DataBinder. Listing 6-19 first sets^3 up a command bean with Sets as
properties.


CHAPTER 6 ■THE CONTROLLER MENAGERIE 133


  1. No pun intended.

Free download pdf