How to bind and validate in MultiActionController

来源:互联网 发布:手机淘宝优惠券怎么用? 编辑:程序博客网 时间:2024/05/20 11:24

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/

原创粉丝点击