Expert Spring MVC and Web Flow

(Dana P.) #1
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().get(0).getFirstName()); // true!
assertEquals("Lala", bean.getNames().get(0).getLastName()); // true!
}

Of course, you aren’t limited to binding to properties of objects inside Lists. You may also
reference a particular Stringinside a Listjust as easily as a Stringproperty of an object in the
List. To illustrate this, take the example command bean shown in Listing 6-13.

Listing 6-13.StringListCommandBean Class

public class StringListCommandBean {

private List<String> strings = new ArrayList<String>();

public List<String> getStrings() {
return strings;
}

public void setStrings(List<String> strings) {
this.strings = strings;
}

}

In this case, to reference the first Stringin the List, the property name would be strings[0].
When you are setting the values, it’s perfectly legal to refer to Strings in the Listin random order,
such as strings[4]and then strings[2]. Of course, if you are trying to read the value of
strings[0]before setting it, you will receive a nullvalue.
Listing 6-14 illustrates how binding directly to Strings inside a Listis performed.

Listing 6-14.StringListCommandBean Unit Test

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

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

130 CHAPTER 6 ■THE CONTROLLER MENAGERIE

Free download pdf