使用 @Valid 进行 Spring 验证

2024-04-26

我正在验证传入属性,但验证器甚至捕获未注释的其他页面@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,
验证器不接受它,但我不想让它验证!通过这个验证器:

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

Spring 不会验证你的IdCommand, but 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(...);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 @Valid 进行 Spring 验证 的相关文章

随机推荐