Expert Spring MVC and Web Flow

(Dana P.) #1

such as firstName, into JavaBean setters, such as setFirstName(). After bind returns, the bean
is populated and ready to be used by the Controller.
If all domain object classes simply had strings for properties and never any child objects,
our discussion could be finished! However, Spring MVC supports and encourages a rich domain
model, and this means the DataBindercan support binding to deeply nested classes, primitives,
and even different types of collections and arrays.


Nested Properties


The real power of the DataBindershows up when binding string values to nested object graphs.
The example in Listing 6-7 used two simple independent properties, a firstNameand lastName.
A reasonable refactoring would move the name properties into a new Nameclass, as shown in
Listing 6-8.


Listing 6-8.NestedCommandBean Class


package com.apress.expertspringmvc.chap4.binding;


public class NestedCommandBean {


private Name name = new Name();

public Name getName() {
return name;
}

public void setName(Name name) {
this.name = name;
}

}


It’s important to see that we initialized the name reference to a non-nullobject. The
DataBinderis not able to set properties on nested objects that are null. Remember that a
string of name.firstNamewill convert to getName().setFirstName("value"). If getName()
returns null, we have a nasty NullPointerExceptionon our hands. This is especially tricky
when it comes to collections, as we will see later. You do not need to initialize the nested
object in exactly the way we have shown (i.e., the same place as the declaration), but be
certain that the object is not nullbefore any binding is to take place.
The firstNameand lastNameproperties are now moved to a Nameclass, shown in Listing 6-9.


Listing 6-9.Name Class


package com.apress.expertspringmvc.chap4.binding;


public class Name {


private String firstName;
private String lastName;

CHAPTER 6 ■THE CONTROLLER MENAGERIE 127
Free download pdf