Spring MVC Validation HTTP Status 400 Bad Request Error

Asked on May 14, 2016
Hi,
I am validating my spring form using annotation.
public class Person {
@Size(min=5, max=20)
private String username;
@Size(min=8, max=15)
private String password;
}
After form submit we are calling below method in my controller.
@RequestMapping(value="addPerson", method = RequestMethod.POST)
public ModelAndView addPerson(@ModelAttribute("person") @Valid Person person, ModelMap model, BindingResult result) {
if(!result.hasErrors()) {
personService.addPerson(person);
}
setPageData(model);
return new ModelAndView("personform");
}
When form has validation error, we are getting HTTP Status 400
Need help.

Replied on May 14, 2016
The order of @ModelAttribute and BindingResult is not correct. BindingResult must be placed just after @ModelAttribute.
You have wrong order, it must be as follows.
public ModelAndView addPerson(@ModelAttribute("person") @Valid Person person, BindingResult result, ModelMap model) {
}
Checkout the spring doc
Invalid ordering of BindingResult and @ModelAttribute.
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pet") Pet pet, Model model, BindingResult result) { ... }
Note, that there is a Model parameter in between Pet and BindingResult. To get this working you have to reorder the parameters as follows:
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result, Model model) { ... }
Find the link

Replied on May 14, 2016
Nice

Replied on October 23, 2017
very good