Tuesday, July 04, 2006

How to bind and validate in MultiActionController

In Spring framework, it provides several controller in MVC model. Personaly, I like the MultiActionController best. And I do not like SimpleFormController because it only one "onSubmit" method. For WEB page, I do not think any page just have one button, i.e: "Save" or "Update". However, SimpleFormController have strong validator ability. But I still hate lots of configure in SimpleFormController.

In Spring MultiActionController, it already provides bind method, however, this method just throws Exception when it find the invalidate error message. To catch this error, we need write a new method to override it.

The goal is to use both MultiActionController and SimpleFormController

Solution: bind and validate in MultiActionController.

In XML, you can write your MultiActionController as normal define.



Now we need bind the form and validator it.

I will use a save action as example:

First create a bindObject method in your BaseContoller (extends MultiActionController)

protected BindException bindObject(HttpServletRequest request,
Object command, Validator validator) throws Exception {
preBind(request, command);
ServletRequestDataBinder binder = createBinder(request, command);
binder.bind(request);

BindException errors = new BindException(command,
getCommandName(command));
if (validator.supports(command.getClass())) {
ValidationUtils.invokeValidator(validator, command, errors);
}

return errors;
}

Now in the save action, you can use this method as normal.

public ModelAndView save(HttpServletRequest request,
HttpServletResponse response, PhoneInfo command) throws Exception {
ModelAndView addPhoneView = new ModelAndView(LIST_VIEW, "phones",
phones);
addPhoneView.addObject("phoneInfo", command);

// add validator and call bindobject to get the result
BindException errors = super.bindObject(request, command, new PhoneInfoValidator());
if (errors.hasErrors()) {
addPhoneView.addAllObjects(errors.getModel());
return addPhoneView;
}

// otherwise --- save this object...
return addPhoneView;
}

In this way, I can easy to fix my problem when I use MultiActionController. I can bind and validate any object as I like.