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.
thanks to ffzhuang :http://ffzhuang.blogspot.com/
本文介绍如何结合使用 Spring MultiActionController 和 SimpleFormController 的优势,通过自定义 bind 和 validate 方法来实现灵活的对象绑定和验证。这种方法允许开发者在 MultiActionController 中进行复杂的表单处理,并利用 SimpleFormController 的强大验证能力。
2064

被折叠的 条评论
为什么被折叠?



