Why does BindingResult have to follow @Valid?

前端 未结 3 1952
遥遥无期
遥遥无期 2020-12-06 06:28

I was struggling to get my Spring MVC validation to return to the page submitted page when I had errors. I finally solved the problem by noticing that BindingResult needs to

相关标签:
3条回答
  • 2020-12-06 07:12

    The BindingResult has to follow the object that is bound. The reason is that if you have more objects that are bound you must know which BindingResult belongs to which object.

    0 讨论(0)
  • 2020-12-06 07:15

    You can potentially have multiple model attributes in your request handler, each with their own binding result. To accomodate this, Spring decided to bind binding result parameters to the previous paramater.

    0 讨论(0)
  • 2020-12-06 07:24

    Yeah, Today I took a long time to check why cannot back to the submitted page but goes to a default whitelable error page.

    After debugging got the source code

    // org.springframework.web.method.annotation.ModelAttributeMethodProcessor#resolveArgument
    if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
        throw new BindException(binder.getBindingResult());
    }
    

    if BindingResult does not follow @Valid , causes isBindExceptionRequired(binder, parameter) return true and then directly throw exception so cannot execute code in controller method.

    // org.springframework.web.method.annotation.ModelAttributeMethodProcessor#isBindExceptionRequired 
    protected boolean isBindExceptionRequired(WebDataBinder binder, MethodParameter methodParam) {
        int i = methodParam.getParameterIndex();
        Class<?>[] paramTypes = methodParam.getMethod().getParameterTypes();
        boolean hasBindingResult = (paramTypes.length > (i + 1) && Errors.class.isAssignableFrom(paramTypes[i + 1]));
        return !hasBindingResult;
    }  
    
    0 讨论(0)
提交回复
热议问题