有条件地设置HTTP状态而不直接操作HttpServletResponse [英] Conditionally setting the HTTP status without directly manipulating the HttpServletResponse
问题描述
如何在Spring MVC请求处理程序中方便地有条件地设置HTTP状态代码?
How can I conveniently conditionally set the HTTP status code in an Spring MVC request handler?
我有一个响应POST请求的请求处理程序,用于创建新资源。如果请求有效,我希望它重定向到新资源的URI,返回201(已创建)HTTP状态代码。如果请求无效,我希望它能让用户有机会更正提交表单中的错误,并且不应该提供201的状态代码。
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.
我不能简单地添加 @ResponseStatus
,因为有两种可能的状态。我希望有一种更简洁的方式,而不是手动操作 HttpServletResponse
。我想指出要使用的视图名称,因此我无法让请求处理程序返回 ResponseEntity
状态设置正确的对象。
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.
推荐答案
如果您需要201响应代码,您可以返回 ResponseEntity 使用 HttpStatus.CREATED 时创建资源,否则创建视图名称。如果是这样,则无法使用重定向(http代码301)。请参阅 RedirectView 。
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.
这篇关于有条件地设置HTTP状态而不直接操作HttpServletResponse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!