Expert Spring MVC and Web Flow

(Dana P.) #1
Binding to Maps
Binding to properties inside objects inside Maps is similar to Lists. The brackets remain, but
instead of a numerical index, you will use the string value of the key inside the map. For
instance, we will modify the command bean to support a Mapof Nameobjects, one for a nick-
name and one for a formal name. Thus, the string expression names['nickname'].firstName
translates to getNames().get("nickname").setFirstName("value")in Java code.
Just like Lists and arrays, you can also bind request parameters directly to objects inside
the Map, instead of properties of objects inside the Map. For instance, if you have a Map<String,
String> stringMap, then you can refer to elements inside the Mapusing the expression
stringMap['key'].
Listing 6-17 is an example of a Mapand nested objects.

Listing 6-17.NestedMapCommandBean Class

public class NestedMapCommandBean {

private Map<String,Name> names = new HashMap<String,Name>();

public NestedMapCommandBean() {
names.put("nickname", new Name());
names.put("formal", new Name());
}

public Map<String, Name> getNames() {
return names;
}
public void setNames(Map<String, Name> names) {
this.names = names;
}

}

Listing 6-18 contains a unit test that illustrates how to use the expression language to refer
to elements in the Map.

Listing 6-18.NestedMapCommandBean Unit Test

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

132 CHAPTER 6 ■THE CONTROLLER MENAGERIE

Free download pdf