Expert Spring MVC and Web Flow

(Dana P.) #1
Listing 6-38.Type Conversion Error Test

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

public void testRequired() {
request.addParameter("intProperty", "NOT_A_NUMBER");

binder.bind(request);

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

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

These two techniques should not be viewed as a replacement for the full validation
framework. The DataBinder’s validation functionality is limited to either declarative required
field checking or automatic type conversion error generation, so for more complicated valida-
tion logic, you will have to use the org.springframework.validationframework. However, it
does generate errors that are fully compatible to the full validation framework. The two types
of validation mechanisms certainly complement each other.
Another thing to note is that typically, you will not have to deal with pulling the
BindExceptionobject out of the DataBinder, or otherwise do any manual checking for
errors. Controllers that implement a full form viewing and submitting work flow (such as
SimpleFormController; see the section after next) will automatically detect the presence of
errors and route the user to the correct view. We presented Listing 6-39 to give you an under-
standing of what is happening under the covers.

Summary


To summarize, the DataBinderis responsible for setting object properties from expression
strings and their values. These expressions, in the form of property.property[2].property,
are the names of HTML fields inside HTML forms. The values come from the submitted HTTP
request parameters. The expression is converted into a series of JavaBean getters and setters
to retrieve or manipulate the data.
The DataBindersupports setting properties of type String, primitives, and nearly any
type, through its use of PropertyEditors. The DataBinder, through its BeanWrapper, supplies
many different PropertyEditors by default, and it is trivial to create and register your own
PropertyEditorto meet your specific needs.

148 CHAPTER 6 ■THE CONTROLLER MENAGERIE

Free download pdf