If you have a Spring-MVC @Controller
for an HTML form and
- You provide a
Validator
for the command object of the form - A form is POST-ed with values that fail validation using that validator
- So the
BindingResult
given to your request handlerhasErrors()
. - Your request handler returns the form view-name as the view name to use, so the user can see the error message(s) and submit a corrected form
What HTTP status code does the reply to the client have? Is it 400 (Bad Request), as we might expect for a RESTful service? That is, does Spring examine the BindingResult
and use the presence of errors to set the status code?
Sample code:
@Controller
public class MyController {
public static class Command {
...
}
public static final String COMMAND = "command";
public static final String FORM_VIEW = "view";
private Validator formValidator = ...
@RequestMapping(value = { "myform" }, method = RequestMethod.POST)
public String processAddCheckForm(
@ModelAttribute(value = COMMAND) @Valid final Command command,
final BindingResult bindingResult) {
if (!bindingResult.hasErrors()) {
// Do processing of valid form
return "redirect:"+uri;
} else {
return FORM_VIEW;
// What status code does Spring set after this return?
}
}
@InitBinder(value = COMMAND)
protected void initAddCheck(WebDataBinder binder) {
binder.addValidators(formValidator);
}
}