gpt4 book ai didi

http - 有条件地设置 HTTP 状态而不直接操作 HttpServletResponse

转载 作者:可可西里 更新时间:2023-11-01 15:12:26 25 4
gpt4 key购买 nike

如何在 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 更简洁的方法.而且我想指出要使用的 View 名称,所以我不能 have the request handler return a ResponseEntity object with the status set appropriately .

最佳答案

如果您需要 201 响应代码,您可以返回 ResponseEntityHttpStatus.CREATED创建资源时,否则为 View 名称。如果是这样,则不能使用重定向(http 代码 301)。参见 RedirectView .

关于http - 有条件地设置 HTTP 状态而不直接操作 HttpServletResponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17238057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com