Why should BindingResult follow @Valid?

I tried to get Spring MVC confirmation to return to the page sent to the page when I had errors. I finally solved the problem by noticing that the BindingResult should be next to the form parameter that I am checking.

For example, if I fix the checkPersonInfo method in the spring.io tutorial ( http://spring.io/guides/gs/validating-form-input/ ) -

@RequestMapping(value="/", method=RequestMethod.POST) public String checkPersonInfo(@Valid Person person, BindingResult bindingResult, Model model) { if (bindingResult.hasErrors()) { return "form"; } return "redirect:/results"; } 

Then it will work and redirect to the form page, but if I change it to -

 @RequestMapping(value="/", method=RequestMethod.POST) public String checkPersonInfo(@Valid Person person, Model model, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return "form"; } return "redirect:/results"; } 

Then it redirects to / errors

What is the reason for this?

+6
source share
3 answers

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

+7
source

In the query handler, you can potentially have several model attributes, each of which has its own binding result. To accommodate this, Spring decided to bind the parameters of the binding result to the previous parameter.

+3
source

Yes, today I spent a lot of time to check why he cannot return to the page presented, but goes to the page with a white error by default.

After debugging, the source code is received

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

if BindingResult does not match @Valid , throws isBindExceptionRequired(binder, parameter) returns true, and then directly throws an exception, so it cannot execute code in the 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; } 
+1
source

Source: https://habr.com/ru/post/983402/


All Articles