Expert Spring MVC and Web Flow

(Dana P.) #1

Binding a Form to a Bean


Spring MVC encourages the use of command beans with a wide variety of property types.
However, the Servlet API returns form parameters only as Strings. To fully take advantage of
richly typed command beans, Spring provides the ability to convert string form parameters
into nearly any other Java class. This technique, called data binding, is the act of taking a name-
value pair, such as name.firstName=joe, and converting it to getName().setFirstName("joe").
Spring MVC uses data binding to set form bean properties from request parameters. This
technique is similar to what is often called an expression language, such as the JSTL’s Expres-
sion Language (EL) or the Object Graph Navigation Language (OGNL). It is very useful as a
shorthand way to refer to bean properties, even deeply nested properties.
The binding functionality is achieved through the use of Spring’s org.springframework.
validation.DataBinderclass and its subclass, org.springframework.web.bind.
ServletRequestDataBinder. As you can see from its package, the DataBinderclass is not
specific to the web framework. This means the capabilities and facilities of data binding are
available to any type of application. The ServletRequestDataBindermerely makes it easy to
bind from Servlet request parameters.
The DataBinderwill happily bind string values to properties of type String. Given
the previous example, the firstNameproperty is a String, so setting the value joeto a String
is trivial. Of course, not every property on every object is a String, so the DataBinder
supports converting a Stringto some arbitrary type via PropertyEditors. We will see more of
PropertyEditors soon, but they are a standard JavaBean mechanism to covert Strings to other
types, such as integers, collections, or nearly any other class. Spring uses PropertyEditors
heavily, and we can take advantage of them as we populate command classes from HTTP
requests.
To be exact, the DataBindermerely coordinates these activities, delegating the actual
binding and PropertyEditorsupport to a BeanWrapper(which we will visit shortly). From
the point of view of a BaseCommandControllerand its subclasses, you will interact with the
DataBinderinstead of BeanWrappers.
It’s best to simply jump in and discover what kind of functionality the DataBindercan
support. To begin with, we will create a simple bean that we will use for the command class.
We will want to take servlet request parameters and bind their values into an instance of a
Name class, shown in Listing 6-5.

Listing 6-5.Example Command Class

package com.apress.expertspringmvc.chap4.binding;

public class Name {

private String firstName;
private String lastName;

public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;

124 CHAPTER 6 ■THE CONTROLLER MENAGERIE

Free download pdf