spring validation with @Valid

后端 未结 1 1539
清酒与你
清酒与你 2021-02-05 22:32

I\'m validating incoming attribute, but the validator catches even the other pages not annotated with @Valid

 @RequestMapping(value = \"/showMatches         


        
1条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-05 23:14

    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 讨论(0)
提交回复
热议问题