Spring:没有调用自定义验证器 [英] Spring: custom validator is not being called

查看:144
本文介绍了Spring:没有调用自定义验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看有关Spring自定义验证器的其他问题,但遗憾的是我无法通过建议的答案解决我的问题。

I was looking at other questions about Spring custom validators but unfortunately I could not solve my problem with the proposed answers.

我的问题如下:我有一个实体(帐户)和我创建了一个自定义验证器(AccountValidator),我在控制器(RegisterController)中使用它,但它永远不会使用默认的验证器调用。

My problem is the following: I have an entity (Account) and I created a custom validator (AccountValidator) which I use in a controller (RegisterController), but it is never invoked, using the default Validator.

Am我忘了什么?我附上部分代码以帮助更好地理解我的问题。

Am I forgetting something? I attach part of the code to help understand better my problem.

验证者:

public class AccountValidator implements Validator{

    @Override
    public boolean supports(Class<?> clazz) {
        return (Account.class).isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {

    //Validation code

    }

}

控制器:

@Controller
@RequestMapping(value = "/register")
public class RegisterController {

    @Autowired
    private AccountValidator accountValidator;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.setDisallowedFields("id");
        binder.setValidator(accountValidator);
    }

    @RequestMapping(method = RequestMethod.GET)
    @ModelAttribute
    public Account register(Locale currentLocale){
        Account account = new Account();
        return account;
    }

    @RequestMapping(method = RequestMethod.POST)
    public String handleRegister(@Valid @ModelAttribute Account account, BindingResult result){
        if(result.hasErrors()){
            return "/register";
        }
        return "home";
    }
}

我检查了日志中的调试信息,正在调用initBinder方法,但验证方法永远不会被执行。

I checked my debug messages in the log, and the initBinder method is being called, but the validation method is never being executed.

任何人都可以帮助我吗?

Can anyone help me?

推荐答案

我遇到了同样的问题,我通过在上下文xml文件中声明类 AccountValidator 并使用 @validated 代替 @valid

I was facing the same issue and i fixed it by declaring the class AccountValidator in context xml file and using @validated in place of @valid.

这篇关于Spring:没有调用自定义验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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