Ajax json交互和SpringMVC中@RequestBody

Ajax json交互和SpringMVC中@RequestBody

标签:


背景

自己提供出去得接口中参数设置为@RequestBody VipPromotionLog vipPromotionLog为一个对象。但是前端人员得处理方式代码如下

    var data = {
        "userId" : 20142100122,
        "userOperationStep" : 2,
        "appPlatform": "android",
        "app" : 0,
        "videoId":123123
    };

    $.ajax({
        url : 'http://localhost:81/online-2c/api/vippromotion',
        type : 'POST',
        dateType : 'json',
        data:data,
        success : function(msg){
            console.log(msg);
        }
    })

问题出现

上述情况出现如图一错误

图一

排查

查看这从请求得类型如图二

图二

content-Type为application/x-www-form-urlencoded
而且传输过去的类型是一个对象,那么我们设置的@RequestBody需要的是什么,难道不是一个对象。这里我个人的理解为@RequestBody需要传输过去的是一个字符串并且和其注释的对象的属性一一对应。

解决

办法一

有两种办法解决 第一不改变后台代码的情况下解决办法如下代码

    var data = {
        "userId" : 20142100122,
        "userOperationStep" : 2,
        "appPlatform": "android",
        "app" : 0,
        "videoId":123123
    };

    $.ajax({
        url : 'http://localhost:81/online-2c/api/vippromotion',
        type : 'POST',
        dateType : 'json',
        contentType : 'application/json',
        data:JSON.stringify(data),
        success : function(msg){
            console.log(msg);
        }
    })

application/json 传输过去的数据为json对象的字符串,data为一个对象,用JSON.stringify转换成对象字符串,其实上面代码和下面的是一样的

   var data = '{\n' +
        '        "userId" : 20142100122,\n' +
        '        "userOperationStep" : 2,\n' +
        '        "appPlatform": "android",\n' +
        '        "app" : 0,\n' +
        '        "videoId":123123\n' +
        '    }';

    $.ajax({
        url : 'http://localhost:81/online-2c/api/vippromotion',
        type : 'POST',
        dateType : 'json',
        contentType : 'application/json',
        data:data,
        success : function(msg){
            console.log(msg);
        }
    })

办法二

修改后台代码,去除@RequestBody注解。这样的话你传输过去的就是一个对象了,并一一对应,如果没有的话就为空。前端js代码不变。

防止

根据前后天的数据交互类型来进行选择。

猜你喜欢

转载自www.cnblogs.com/Krloypower/p/9277117.html