【发布时间】:2013-06-21 14:42:54
【问题描述】:
如何在 Spring MVC 请求处理程序中方便地有条件地设置 HTTP 状态代码?
我有一个响应 POST 请求的请求处理程序,用于创建新资源。如果请求有效,我希望它重定向到新资源的 URI,返回 201(已创建)HTTP 状态代码。如果请求无效,我希望它让用户有机会更正提交表单中的错误,并且不应该提供状态代码 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";
}
}
但这并没有为重定向案例提供正确的响应状态。
我不能简单地添加@ResponseStatus,因为有两种可能的状态。我希望有比manually manipulating the HttpServletResponse 更简洁的方法。而且我想指明要使用的视图名称,所以我不能have the request handler return a ResponseEntity object with the status set appropriately。
【问题讨论】:
标签: http spring-mvc http-status-codes