Expert Spring MVC and Web Flow

(Dana P.) #1
binder.bind(request);

assertEquals("Anya", bean.getStrings().get(0)); // true!
assertEquals("Lala", bean.getStrings().get(1)); // true!
}


Binding to Arrays


Arrays work in an identical manner to Lists. The DataBinderexpression for an array is the
same as for the List. Listing 6-15 changes a Listof Nameobjects into an array.


Listing 6-15.NestedArrayCommandBean Class


public class NestedArrayCommandBean {


private Name[] names = new Name[]{new Name(), new Name()};

public Name[] getNames() {
return names;
}
public void setNames(Name[] names) {
this.names = names;
}

}


The unit test, contained in Listing 6-16, looks nearly identical, and the binding expres-
sions remain the same. As with Lists, when binding properties to objects in arrays, make sure
the object exists in the array first. The DataBinderwon’t create a new instance of the object if it
is null; instead it will generate a NullPointerException.


Listing 6-16.NestedArrayCommandBeanTest


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


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


binder.bind(request);

assertEquals("Anya", bean.getNames()[0].getFirstName()); // true!
assertEquals("Lala", bean.getNames()[0].getLastName()); // true!
}


CHAPTER 6 ■THE CONTROLLER MENAGERIE 131
Free download pdf