使用@Valid进行弹簧验证

cou*_*ech 11 validation spring spring-mvc

我正在验证传入属性,但验证程序甚至可以捕获未注释的其他页面 @Valid

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

当我访问页面时,/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,
验证器不接受它,但我不想让它验证!通过此验证器:

 protected void initBinder(WebDataBinder binder) {
        binder.setValidator(new Validator() {
  // etc.
}
Run Code Online (Sandbox Code Playgroud)

axt*_*avt 24

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

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

@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(...);
}
Run Code Online (Sandbox Code Playgroud)