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 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'}

前端网络抓包
springMVC使用@RequestBody接收Json的过程,解决415的问题ss_第1张图片

你可能感兴趣的:(JAVA,EE)