问题
Would it be possible to have multiple initBinder Methods inside a single Controller? Where each InitBinder() (see code) depends on a unique request handler e.g. initBinder() is called on url: "/update/account" and initBinderOne() on "update/account/pass"?
I would prefer to have a single Controller for all updates instead of multiple. Please advise.
@Controller
@RequestMapping(value="/uodate/account")
public class UpdateController {
@RequestMapping(method=RequestMethod.GET)
public String updateAccount(@ModelAttribute("account") Account account...){
..
}
@RequestMapping(method=RequestMethod.POST)
public String update(@Valid Account account...){
...
}
@RequestMapping(value="/pass", method=RequestMethod.GET)
public String updatePass(@ModelAttribute("account") Account account...){
...
}
@RequestMapping(value="/pass",method=RequestMethod.POST)
public String updatePass(@Valid Account account...){
...
}
@InitBinder("account")
public void initBinder(WebDataBinder binder){
binder.setValidator(validateAccount);
binder.setAllowedFields(new String[]{"accountId","accountname","firstName",
"lastName","address"});
}
@InitBinder("account")
public void initBinderOne(WebDataBinder binder){
binder.setValidator(validatePassword);
binder.setAllowedFields(new String[]{"accountId","password});
}
回答1:
Spring does not support attaching multiple validators to a single command. You can, however, define multiple @InitBinder methods for different commands. For example, you could put the following in a single controller and validate your user1 and user2 parameters:
@InitBinder("user1")
protected void initUser1Binder(WebDataBinder binder) {
binder.setValidator(new User1Validator());
}
@InitBinder("user2")
protected void initUser2Binder(WebDataBinder binder) {
binder.setValidator(new User2Validator());
}
来源:https://stackoverflow.com/questions/17948762/how-to-define-multiple-initbinders