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.
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With