Conditionally setting the HTTP status without directly manipulating the HttpServletResponse

假装没事ソ 提交于 2019-12-05 20:24:22

问题


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.



来源:https://stackoverflow.com/questions/17238057/conditionally-setting-the-http-status-without-directly-manipulating-the-httpserv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!