Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally setting the HTTP status without directly manipulating the HttpServletResponse

How can I conveniently conditionally set the HTTP status code in an Spring MVC request handler?

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.

 @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";
  }

}

But that does not give the correct response status for the redirection case.

I can't simply add a @ResponseStatus, because there are two possible statuses. I'm hoping there is a neater way than manually manipulating the HttpServletResponse. And I want to indicate the view name to use, so I can not have the request handler return a ResponseEntity object with the status set appropriately.

like image 289
Raedwald Avatar asked Jun 21 '13 14:06

Raedwald


People also ask

What method sets the status code for the HTTP response?

setStatus. Sets the status code for this response. This method is used to set the return status code when there is no error (for example, for the status codes SC_OK or SC_MOVED_TEMPORARILY).

How would you specify HTTP status codes to return from your controller?

Sending Specific Response Status Codes The very basic way of sending response status is to use ResponseEntity object, which is returned by a controller. Controller can set a specific response status in the Response. Alternatively, we can use @ResponseStatus annotation to specify the desired status code.

How do I get HTTP status code from response in spring boot?

We can use @ResponseStatus annotation to mark a method or an Exception class with a Status code and reason to be returned. On invoking the marked handler method or when a specified exception is thrown, the HTTP status will be set to the one defined using @ResponseStatus annotation.


1 Answers

In case you want a 201 response code, you can return a ResponseEntity with HttpStatus.CREATED when the resource is created and the view name otherwise. If so, you cannot use a redirect (http code 301). See RedirectView.

like image 177
Robert Avatar answered Oct 11 '22 07:10

Robert