springMVC使用@RequestBody接收Json的过程,解决415的问题ss

今天学习SpringMVC过程中,遇到了用@RequestBody接收Json的问题,开始总是报415,后来翻墙找到了解决办法,本人用的Spring4

Spring配置文件所必须最简配置:

<context:annotation-config />
<mvc:annotation-driven />
<bean id="jacksonMessageConverter"
 class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>

依赖配置,本人用的gradle

compile 'com.fasterxml.jackson.core:jackson-core:2.6.3'
compile 'com.fasterxml.jackson.core:jackson-databind:2.6.3'

后端代码

 @RequestMapping(value = "saveUser", method = {RequestMethod.POST})
    @ResponseBody
    public void saveUser(@RequestBody List<User> users) {
        for (User user : users) {
            System.out.println(user.toString());
        }
    }
public class User {
    private String userName;
    private String address;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + userName + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

前端代码

$(document).ready(function(){
    var saveDataAry=[];
    var data1={"userName":"test","address":"gz"};
    var data2={"userName":"ququ","address":"gr"};
    saveDataAry.push(data1);
    saveDataAry.push(data2);
    $.ajax({
        type:"POST",
        url:"saveUser",
        dataType:"json",
        contentType:"application/json",
        data:JSON.stringify(saveDataAry),
        success:function(data){

        }
    });
});

实验结果

User{username='test', address='gz'}
User{username='ququ', address='gr'}

前端网络抓包
网络抓包图片

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值