Search code examples
formsvalidationspring-mvchttp-status-codes

HTTP status returned by Spring MVC for a form POST that fails validation


If you have a Spring-MVC @Controller for an HTML form and

  1. You provide a Validator for the command object of the form
  2. A form is POST-ed with values that fail validation using that validator
  3. So the BindingResult given to your request handler hasErrors().
  4. 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);
    }
 }

Solution

  • The status code is, perhaps surprisingly, not 400 (Bad Request), but 200 (OK).

    This is presumably to ensure that the user's web browser will display the form with its error messages, rather than a generic 400 (Bad Request) error page. However, Firefox seems OK if you have your request handler sets the status code to 400 for this case.