How to define multiple initBinders

我是研究僧i 提交于 2019-12-06 08:04:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!