【问题标题】:RequestMapping with POST in Spring not working?在 Spring 中使用 POST 的 RequestMapping 不起作用?
【发布时间】:2021-06-12 04:47:57
【问题描述】:

您好,我的客户端有以下 ajax 调用。

 var arr = JSON.stringify(JSON_Array);
 $.ajax({
            url: 'http://localhost:8080/',
            type: 'POST',
            data: arr,
            dataType: 'text',
            contentType: 'application/json',
            success: function () {
                console.log("Success!");
            },
            error: function() {
                console.log("error");
            },
            
        });

服务器端:

@Controller
public class Controller{
    @RequestMapping("/")
    public String start() {
        System.out.println("works"); //prints
        return "index";
    }

    @RequestMapping(value = "/", method = RequestMethod.POST, consumes = "text/plain")
    public void process(@RequestBody String payload) throws Exception {
        System.out.println("payload "  + payload); //does not print
    }
}

ajax 调用成功发送,但是服务器端没有收到任何内容。未使用处理方法。我不太清楚为什么。帮助将不胜感激。

编辑: @Toofy 评论后所做的更改

在 Ajax 调用中:

dataType: 'text',
contentType: "text/plain;",

工艺方法保持不变。

我还尝试将 Ajax 调用更改为以下内容

dataType: 'json',
contentType: "application/json;",

服务器端发生变化:

@RequestMapping(value = "/", method = RequestMethod.POST, consumes = "application/json")
    public void process(@RequestBody String payload) throws Exception {
        System.out.println("payload "  + payload);
    }

在这两种情况下,ajax 调用都会停止工作

【问题讨论】:

  • 我认为这是因为您将其作为 json 发送,并且您的处理方法明确要求 text/plain ?
  • @Toofy 我已对您的评论进行了编辑
  • start() 应该是 GET 方法吗?
  • 这是一种加载模板文件夹中 index.html 页面的方法。它与 thymleaf 一起运行

标签: java ajax spring spring-boot spring-mvc


【解决方案1】:

通过执行以下操作使其工作:

在 Ajax 调用中我摆脱了 dataType

$.ajax({
      url: 'http://localhost:8080/',
      type: 'POST',
      data: arr,
      contentType: "application/json; charset=utf-8",          
});

在服务器端我将处理方法改为

@RequestMapping(value = "/", method = RequestMethod.POST)
@ResponseBody
public void process(@RequestBody String payload) throws Exception {
    System.out.println(payload);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多