You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ajax向Spring MVC控制器发送JSON数据失败求助

解决Ajax向Spring MVC控制器发送JSON无法接收数据的问题

我帮你排查几个常见的问题点,应该能解决你的JSON数据接收失败的问题:

1. 控制器方法必须添加@RequestBody注解

你的Spring MVC代码没写完,但大概率是没加@RequestBody——这个注解是告诉Spring要从请求体里解析JSON数据,绑定到Java对象上。正确的控制器写法应该是这样:

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController // 用这个注解,或者@Controller+@ResponseBody
public class MyController {

    @RequestMapping(value = "/j", method = RequestMethod.POST)
    public ResponseEntity<String> receiveData(@RequestBody User user) {
        // 这里就能拿到pName和lName了
        System.out.println("Received pName: " + user.getPName());
        System.out.println("Received lName: " + user.getLName());
        return ResponseEntity.ok("Data received successfully");
    }
}

同时你需要一个对应的实体类User,属性名要和JSON里的key完全匹配,还要有无参构造器和getter/setter:

public class User {
    private String pName;
    private String lName;

    // 必须要有无参构造器,Spring反射创建对象需要
    public User() {}

    // getter和setter方法
    public String getPName() {
        return pName;
    }

    public void setPName(String pName) {
        this.pName = pName;
    }

    public String getLName() {
        return lName;
    }

    public void setLName(String lName) {
        this.lName = lName;
    }
}

2. 确保Spring MVC支持JSON解析

你需要引入Jackson的依赖,这样Spring才能把JSON转换成Java对象:

  • 如果是Maven,在pom.xml里加:
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.15.2</version> <!-- 用最新稳定版就行 -->
    </dependency>
    
  • 配置上要开启注解驱动:
    • XML配置:添加<mvc:annotation-driven/>
    • Java配置:在配置类上加@EnableWebMvc注解,或者继承WebMvcConfigurer

3. 完善Ajax请求的细节

你的Ajax代码大体没问题,但可以加上error回调排查错误,还可以明确dataType:

var search = { "pName" : "bhanu", "lName" :"prasad" };
var enviar = JSON.stringify(search);
$.ajax({
    type: "POST",
    contentType : 'application/json; charset=utf-8',
    url: 'http://localhost:8080/HelloSpringMVC/j',
    data: enviar,
    dataType: "json", // 明确期望响应是JSON格式
    success :function(result) {
        console.log("请求成功:", result);
    },
    error: function(xhr, status, err) {
        // 打印错误信息,方便排查
        console.log("请求错误状态:", status);
        console.log("错误详情:", xhr.responseText);
    }
});

4. 用浏览器开发者工具验证请求

打开浏览器F12的Network标签,找到你发送的POST请求,查看:

  • Request Headers里的Content-Type是不是application/json; charset=utf-8
  • Request Body里是不是正确的JSON字符串:{"pName":"bhanu","lName":"prasad"}

如果这些都没问题,控制器应该就能正常接收数据了。

内容的提问来源于stack exchange,提问作者sgm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:35:33