Spring MVCb数据绑定-简单对象

说明:当Ajax以application/x-www-form-urlencoded格式上传即使用JSON对象,后台需要使用@RequestParam 或者Servlet获取。 当Ajax以application/json格式上传即使用JSON字符串,后台需要使用@RquestBody获取。

Spring MVC转换配置:

方式一、application/x-www-form-urlencoded时

Model:

public class TestInfo implements Serializable {

    private String id;
    private String name;

    public TestInfo() {
    }

    public TestInfo(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getId() {
        return this.id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Controller:
@RequestMapping(value = "/t4",method = RequestMethod.POST)
@ResponseBody
public void createTestInfo2(HttpServletRequest request, HttpServletResponse response,
                            TestInfo testInfo) {
    System.out.println(testInfo.getId() + testInfo.getName());
}

Ajax: 此处没有设置content-type,默认请求为application/x-www-form-urlencoded

$("#testInfo3").click(function () {
    var tetsInfo3 = {
        id:"123",
        name:"456",
    };
    $.ajax({
        url:'http://127.0.0.1:8089/server/tarry/t4',
        type:'post',
        data:tetsInfo3,
        dataType:'json',
        success:function(data){
            console.log(data);
        }

    });
});

方式二、application/json时

Model:

public class TestInfo implements Serializable {

    private String id;
    private String name;

    public TestInfo() {
    }

    public TestInfo(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getId() {
        return this.id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Controller:
@RequestMapping(value = "/t3",method = RequestMethod.POST)
@ResponseBody
public void createTestInfo1(HttpServletRequest request, HttpServletResponse response,
                            @RequestBody TestInfo testInfo) {
    System.out.println(testInfo.getId() + testInfo.getName());
}

Ajax: 此处设置content-type=application/json

$("#testInfo2").click(function () {
    var tetsInfo2 = {
        id:"123",
        name:"fang",
    };
    $.ajax({
        url:'http://127.0.0.1:8089/server/tarry/t3',
        type:'post',
        contentType: "application/json",//设置contentType为application/json
        data:JSON.stringify(tetsInfo2),
        dataType:'json',
        success:function(data){
            console.log(data);
        }

    });
});

猜你喜欢

转载自blog.csdn.net/u010299087/article/details/81703029