Wednesday, May 7, 2014

Comparing validator registering for bean in Spring 2.5 and 3.1

Validating a bean using a validator class is a common practice in Spring.

For Spring 2.5

validators are registered to a form where the validator validates the form backing object.

<bean id="myForm" class="net.example.web.MyForm">
        <property name="validator"><ref bean="myValidator"/></property>

<bean id="myValidator" class="net.example.web.MyValidator">

When a post is recieved

protected void onBind(HttpServletRequest request, Object command, BindException errors) throws Exception

is called which (If validateOnBinding is set), invokes a registered Validator. The Validator checks the form object properties, and register corresponding errors via the given Errors
object if any validation error is found then showForm method is called to show the form again with the validation errors. So once a validator is registered nothing else needs to be done to invoke validation.

in spring 3 its a bit different. One might think that registering the validator will be enough here and the session object will be validated automatically. But in Spring 3.1 Registering a validator isn't enough.

@InitBinder(value = "myObject")
    public void initBinder(WebDataBinder binder) {

to validate it using a validator class you must use @Validate annotation as well.

@RequestMapping(value = "/submit", params="update", method=RequestMethod.POST)
    public String updateMyObject(@Validated @ModelAttribute("myObject) MyObject myObject,                                   BindingResult result) throws WebSecurityException {

//and check for binding errors in BindingResult result object

if (result.hasErrors()) {
            return VIEW_PAGE;

No comments:

Post a Comment