Expert Spring MVC and Web Flow

(Dana P.) #1
To allow certain properties, simply call the setAllowedFields()method with a full list of
all properties to be considered for binding. You will need to set this list before binding will take
place.
The example in Listing 6-36 illustrates how to secure the binding process to only bind
allowed fields. We’re using the simple Nameclass (Listing 6-5) for this example, and we prohibit
the lastNamefrom being bound.

Listing 6-36.Allowed Fields Test

public void setUp() {
name = new Name();
binder = new ServletRequestDataBinder(name, "name");
request = new MockHttpServletRequest();
}

public void testAllowedFields() {
// only allow firstName field, ignore all others
binder.setAllowedFields(new String[]{"firstName"});

request.addParameter("firstName", "First");
request.addParameter("lastName", "Last");

binder.bind(request); // only print log message on non-allowed fields
// allow binding to continue

assertEquals("First", name.getFirstName());
assertNull(name.getLastName());
}

By specifying which fields should be allowed for a particular binding, you can ensure
that only intended fields from the HTML form will eventually make their way into the domain
objects. Otherwise, there is no protection from misconfigured or malicious request parameters.

Rudimentary Validation
While Spring MVC support’s Spring’s flexible validation framework (covered in great detail in
Chapter 9), the DataBinderprovides a sort of “first line of defense” through its basic validation
support. The DataBindercan be configured to check for required fields, or type mismatches,
and any errors from these rules flow right into the main Validation system.
Although we will dedicate an entire chapter to Spring MVC’s validation framework, to
fully understand the DataBinder’s basic validation support we will very briefly cover some of
the fundamental constructs here. For every instance of data binding, there is a corresponding
instance of a org.springframework.validation.BindException. This object is created automat-
ically when binding begins, and encapsulates all the errors—either general object errors or
field level errors—resulting from the binding and validation process.

146 CHAPTER 6 ■THE CONTROLLER MENAGERIE

Free download pdf