Expert Spring MVC and Web Flow

(Dana P.) #1

expected = new PhoneNumber();
expected.setAreaCode("222");
expected.setPrefix("333");
expected.setSuffix("4444");
}


public void testBind() {
PhoneNumberEditor editor = new PhoneNumberEditor();
binder.registerCustomEditor(PhoneNumber.class, editor);


request.addParameter("phoneNumber", "(222) 333-4444");

binder.bind(request);
assertEquals(expected.getAreaCode(), bean.getPhoneNumber().getAreaCode());
assertEquals(expected.getPrefix(), bean.getPhoneNumber().getPrefix());
assertEquals(expected.getSuffix(), bean.getPhoneNumber().getSuffix());
}


This all works because the property on the command bean is of type PhoneNumber, so
the PhoneNumberPropertyEditorcan easily be called upon to do the Stringto PhoneNumber
conversion. There is no limit to the number of PropertyEditors you can declare and register
to a DataBinder. You can also replace a registered PropertyEditorin the DataBinderif you wish
to redefine which editor is called upon for each class.
As mentioned, you may also choose to map each property of the PhoneNumberclass to a
HTML text field. In this case, you will not need a custom PropertyEditor. However, if you find
that you need to use a single text field to contain the entire value of a bean, even if that bean
has multiple properties, then a custom PropertyEditorwill allow you to handle this scenario.
In other words, when you need to convert a single Stringvalue into a single complex object
(potentially with many properties of its own), use a custom PropertyEditor.


Controlling Which Fields Are Bound


By default, the DataBinderwill bind to any property on a bean that it can. That is, if the HTTP
request contains a parameter name that matches a property of the bean, the bean’s setter for
that property will be called. Depending on the situation, this may or may not be what you will
want. It is possible to control when fields can become bound, in order to provide an extra
layer of protection from outside manipulation.
For instance, in Spring MVC, it’s very common to bind request parameters directly to
domain object models. Although this streamlines development and reduces the amount of
classes in the system, it does present a potential security risk for the system. The binding
process exposes the domain object directly to outside information. An attacker can, if enough
knowledge of the system is gained, manipulate the domain object by sending an unintended
request property and value with the form submit. This action would potentially bypass valida-
tion, and otherwise incur a risky situation.
To provide extra security for handling incoming data, the DataBindercan be configured to
allow only accepted and approved properties. Properties not in the approved list will be
dropped, and binding will continue.


CHAPTER 6 ■THE CONTROLLER MENAGERIE 145
Free download pdf