本文介绍了使用@Valid进行春季验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在验证传入属性,但是验证器甚至捕获了其他未用@Valid注释的页面

I'm validating incoming attribute, but the validator catches even the other pages not annotated with @Valid

 @RequestMapping(value = "/showMatches.spr", method = RequestMethod.GET)
    public ModelAndView showMatchPage(@ModelAttribute IdCommand idCommand)
//etc

访问页面/showMatches.spr时出现错误org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: Invalid target for Validator [cz.domain.controller.Controllers$1@4c25d793]: cz.domain.controller.IdCommand@486c1af3
验证器不接受它,但是我不希望它进行验证!通过此验证器:

When I access page /showMatches.spr I get the error org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: Invalid target for Validator [cz.domain.controller.Controllers$1@4c25d793]: cz.domain.controller.IdCommand@486c1af3,
The validator doesn't accept it, but I don`t want it to validate! By this validator:

 protected void initBinder(WebDataBinder binder) {
        binder.setValidator(new Validator() {
  // etc.
}

推荐答案

Spring不会验证您的IdCommand,但是WebDataBinder不允许您设置不接受bean的验证器绑定.

Spring isn't going to validate your IdCommand, but WebDataBinder doesn't allow you to set a validator that doesn't accept the bean being bound.

如果使用@InitBinder,则可以显式指定要由每个WebDataBinder绑定的模型属性的名称(否则,将initBinder()方法应用于所有属性),如下所示:

If you use @InitBinder, you can explicitly specify the name of the model attribute to be bound by each WebDataBinder (otherwise your initBinder() method is applied to all attributes), as follows:

@RequestMapping(...)
public ModelAndView showMatchPage(@ModelAttribute IdCommand idCommand) { ... }

@InitBinder("idCommand")
protected void initIdCommandBinder(WebDataBinder binder) {
    // no setValidator here, or no method at all if not needed
    ...
}

@RequestMapping(...)
public ModelAndView saveFoo(@ModelAttribute @Valid Foo foo) { ... }

@InitBinder("foo")
protected void initFooBinder(WebDataBinder binder) {
    binder.setValidator(...);
}

这篇关于使用@Valid进行春季验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 23:28