SpringMvc处理ajax请求json

pom.xml 引入依赖包
   <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
    
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
    </dependency>
    
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.0</version>
    </dependency>
User实体类
//三个属性
private String username;
private String password;
private Integer age;

jQuery ajax请求函数 发送post请求
function ajax() {
        $.ajax({
            url:"user/testAjax",
            contentType:"application/json;charset=UTF-8",
            data:'{"username":"hehe","password":"123","age":20}',
            dataType:"json",
            type:"post",
            success:function (data) {
                console.log(data)
            }
        })
    }
@Controller类
@RequestMapping(value = "/testAjax") 
public @ResponseBody User testAjax(@RequestBody User user){
       //user为ajax请求发送过来的json通过springmvc自动转换为实体类
       //json的对象内容和实体类属性值相同
       System.out.println(user);
       //打印结果为post请求的对象(自动从json转换为user对象)
       return user;
    }
post发送请求的请求体为json对象,json对象的内容为实体类的属性,实体类属性值和请求的json对象里面的值是相同的,然后通过springmvc自动将请求的json转换成了实体类对象
//JQuery请求体
data:'{"username":"hehe","password":"123","age":20}'
//实体类 注意要实现序列化接口
public class User implements Serializable {
private String username;
private String password;
private Integer age;
//相应的get,set方法
get...set...
}
注意:要从json转换到的实体类要实现Serializable接口
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值