【问题标题】:Change the request method from POST to GET in a redirection from spring controller在 spring 控制器的重定向中将请求方法从 POST 更改为 GET
【发布时间】:2019-02-01 22:24:51
【问题描述】:

我有一个 spring mvc 控制器,它接受一个 post 请求,它需要重定向到一个 URL(GET 请求)。

@RequestMapping(value = "/sredirect", method = RequestMethod.POST)
public String processForm(HttpServletRequest request) {
    System.out.println("Ews redirect hit !!! ");
request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE,HttpStatus.MOVED_PERMANENTLY);
    
    return "redirect:https://www.google.com/";
}

并且该类使用@RestController 进行注释。我总是收到 405,重定向 url 不允许的方法。 (即 google.com)。

根据文档 (https://www.rfc-editor.org/rfc/rfc7238),它应该允许更改方法。我不确定我做错了什么?有人可以帮忙吗

【问题讨论】:

  • 听起来你得到的是 405 而不是你的日志记录,对吗?您是否正在对您的 /sredirect 进行 HTTP POST?这是这个控制器唯一能接受的。
  • 不,我的日志正在控制台中正确打印,.
  • 好的,基于此,我认为 RestControllers 不能简单地返回“redirect:”,就像非 Rest Controller 可以:stackoverflow.com/questions/29085295/…(不作为答案添加,因为我其实不知道:-))
  • @dbreaux 你是对的,链接中提到的解决方案对我有用。您可以将此添加为答案,我会接受。 :)

标签: java rest spring-mvc web


【解决方案1】:

您是否尝试在请求映射中接受 GET?

method = { RequestMethod.POST, RequestMethod.GET }

【讨论】:

  • 嗯好的。也许将函数更改为返回类型 void 并调用 request.sendRedirect("https://www.google.com"); 而不是返回。
【解决方案2】:

看起来 Rest Controller 不能使用简单的“redirect:”约定,就像 non-Rest Controller 一样。见Spring MVC @RestController and redirect

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-13
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 2021-12-20
    • 2016-02-21
    • 2018-01-10
    相关资源
    最近更新 更多