Conditionally setting the HTTP status without dire

2019-04-07 06:24发布

问题:

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.

回答1:

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.