我正在验证传入的属性,但验证器甚至会捕获未使用 @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;嵌套异常是 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
,但 WebDataBinder
不允许您设置不接受绑定(bind)的 bean 的验证器。
如果你使用@InitBinder
,你可以显式指定每个WebDataBinder
要绑定(bind)的模型属性的名称(否则你的initBinder()
code> 方法应用于所有属性),如下:
@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 进行 Spring 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3721122/