首页 > 解决方案 > Spring:从 POST 方法重定向不起作用

问题描述

我正在尝试让我的 Spring 控制器接收 POST 请求。我想获取发布请求的正文并将其显示在网页上。我通过邮递员发送请求。我的控制器接收到它,但不知何故,当我像往常一样尝试重定向到另一个页面时,Spring 呈现 html 模板并将其发送回 Postman。

我的代码:

@GetMapping("/webhooks")
public String webhooks(Model model) {
    model.addAttribute("response", "webhooks");
    return "connected";

@PostMapping("/webhooks")
public String webhooks(String payload, Model model) {
    model.addAttribute("response", payload);
    return "connected";
}

我的 connected.html 模板:

<body>
<a href="/" >Home</a>
<h3>Connected!</h3>
<div>
  <button onclick="refreshToken()">Refresh Token</button>
  <br /><br />
  <button onclick="newCustomer()">Create new customer</button>
  <button onclick="invoice()">Create new invoice</button>
  <br />
  <div><code id="result" th:text="${response}"></code></div>
</div>
</body>

这是我在 Postman 窗口中看到的: 图片链接

但我希望在我的浏览器而不是 Postman 中看到相同的表单(如图所示)。我想重定向到这个页面,而不是把这个页面发回 Postman。我在其他控制器中有一些类似的方法,它们完全相同,但它们工作正常。

我究竟做错了什么?先感谢您。

标签: springhttpspring-mvcpostman

解决方案


我和你有同样的问题,我尝试了不同的方法来解决这个问题,但没有一个对我有用。但是你可以试一试:

@GetMapping("/webhooks")
public RedirectView webhooks(Model model) {
    //Do what you want
    return new RedirectView("/connected");

@PostMapping("/webhooks")
public RedirectView webhooks(String payload, Model model) {
    //Do what you want
    return new RedirectView("/connected");
}

这对我没有用,但它可能会帮助你。您使用 Spring 中的 RedirectView 类并输入端点的 URL。

请让我知道它是否对您有用!


推荐阅读