Expert Spring MVC and Web Flow

(Dana P.) #1

Errors that apply to the entire object being bound to are instances of org.springframework.
validation.ObjectErrorand are created when a validation rule that is not specific to any field
is violated. Errors that are field-specific are instances of org.springframework.validation.
FieldError. These error types are more common, as they encapsulate the specific error (e.g.,
a required field is missing) and the field that caused the error.
Configuring the DataBinderto check for required fields is similar to enforcing allowed
fields (see the previous section, “Controlling Which Fields Are Bound”). By calling the
setRequiredFields()method with a list of properties, the DataBinderwill register an
error if that property is missing from the request parameters. The error is an instance of
org.springframework.validation.FieldErrorand is added to the DataBinder’s instance
of org.springframework.validation.BindException.
For the example, we will use the trusty Nameclass, and we will require the presence of the
firstNamefield. Listing 6-37 contains the unit test illustrating required fields.


Listing 6-37.Required Field Validation Test


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


public void testRequired() {
binder.setRequiredFields(new String[]{"firstName"});


// missing firstName parameter
request.addParameter("lastName", "Smith");

binder.bind(request);

BindException errors = binder.getErrors();
FieldError error = errors.getFieldError("firstName");

assertNotNull(error); //true!
assertEquals("required", error.getCode()); //true!
}


The DataBinderwill also generate an error if the request parameter value cannot be
coerced into the field’s type. For instance, if the parameter value is Smithbut the field type
is a java.lang.Integer, the DataBinderwill intelligently create an error for this situation.
This behavior, in fact, is automatic, and requires no explicit configuration on the DataBinder.
For the example, we will use a MultiTypeCommandBean(Listing 6-24) and attempt to set
a Stringvalue into intPropertyfield, which is an int. Listing 6-38 contains the unit test
illustrating error generation.


CHAPTER 6 ■THE CONTROLLER MENAGERIE 147
Free download pdf