如何定义多个initBinders [英] How to define multiple initBinders

查看:295
本文介绍了如何定义多个initBinders的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个Controller内是否可以有多个initBinder方法?每个InitBinder()(请参见代码)都取决于唯一的请求处理程序,例如在URL:"/update/account"上调用initBinder(),在"update/account/pass"上调用initBinderOne()吗?

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});

    }   

推荐答案

Spring不支持将多个验证器附加到单个命令.但是,您可以为不同的命令定义多个@InitBinder方法.例如,您可以将以下内容放在单个控制器中,并验证您的user1和user2参数:

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());
}

这篇关于如何定义多个initBinders的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆