【问题标题】:spring validation with @Valid使用@Valid 进行春季验证
【发布时间】:2010-09-15 19:31:22
【问题描述】:

我正在验证传入的属性,但验证器甚至会捕获其他未使用 @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 spring-mvc validation


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多