Expert Spring MVC and Web Flow

(Dana P.) #1

Binding to Collections


Along with nested classes, the DataBindersupports binding properties of objects inside collec-
tions. Your command bean class and its nested classes can contain Lists, Maps, and arrays.
Just like nested classes, the object in the collection that you are attempting to set a prop-
erty value on must not be null. This means that, before binding, you must not only initialize
the collection, but populate it with objects.


Binding to Lists


To begin, we will create a new command bean that contains a Listof Nameobjects, as shown in
Listing 6-11.


Listing 6-11.NestedCollectionsCommandBean Class


public class NestedCollectionsCommandBean {
private List names = new ArrayList();


public NestedCollectionsCommandBean() {
names.add(new Name());
names.add(new Name());
}

public List getNames() {
return names;
}
public void setNames(List names) {
this.names = names;
}
}


Notice how we not only had to initialize the List, but also populate it. We added two Name
objects into the list in the constructor for convenience, but normally the objects will be added
as the result of some web request or business logic.
The DataBinderuses a familiar [index]notation to reference items in a Listor array. For
instance, the string names[0].firstNameis the same as getNames().get(0).setFirstName("value").
Listing 6-12 shows an example of binding to object properties inside collections.


Listing 6-12.NestedCollectionsCommandBeanTest


public void setUp() throws Exception {
bean = new NestedCollectionsCommandBean();
binder = new ServletRequestDataBinder(bean, "beanName");
request = new MockHttpServletRequest();
}


CHAPTER 6 ■THE CONTROLLER MENAGERIE 129
Free download pdf