title: Conditionally setting the HTTP status without directly manipulating the HttpServletResponse
body: <p>How can I conveniently conditionally set the HTTP status code in an Spring MVC request handler?</p>
  
  <p>I have a request handler that responds to POST requests, for creation of a new resource. If the request is valid I want it to redirect to the URI of the new resource, returning a 201 (Created) HTTP status code. If the request is invalid I want it to give the user a chance to correct the error in the submitted form, and should not give a status code of 201.</p>
  
  <pre><code> @RequestMapping(value = { "/myURI/" }, method = RequestMethod.POST)
   public String processNewThingForm(
      @ModelAttribute(value = "name") final String name,
      final BindingResult bindingResult) {
  
    myValidator.validate(name, bindingResult);
  
    if (!bindingResult.hasErrors()) {
       getService().createThing(name);
       return "redirect:" + name;
    } else {
       return "newThingView";
    }
  </code></pre>
  
  <p>}</p>
  
  <p>But that does not give the correct response status for the redirection case.</p>
  
  <p>I can't simply add a <code>@ResponseStatus</code>, because there are two possible statuses. I'm hoping there is a neater way than <a href="https://stackoverflow.com/questions/678433/setting-response-status-code-manually?">manually manipulating the <code>HttpServletResponse</code></a>. And I want to indicate the view name to use, so I can not <a href="https://stackoverflow.com/a/16250729/545127">have the request handler return a <code>ResponseEntity</code> object with the status set appropriately</a>.</p>