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.

 

thanks to ffzhuang :http://ffzhuang.blogspot.com/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值