开发者

spring validation with @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

When I access page /showMatches.spr I get the error org.springframework.web.util.N开发者_如何转开发estedServletException: 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 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.

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(...);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜