springmvc接收ajax请求参数遇到的坑

ajax发送请求后台接收不到参数

做项目的过程中,springmvc Controller接收前端ajax请求参数总是接收不到,为null值,具体代码如下:
前端ajax代码:

$.ajax({
        headers: {
            'Content-type': 'application/json; charset=utf-8'
        },
        url : getContextPath()+"/groupUserRel/insert",
        data :{
            "groupId": "80901",
            "userName": name,
            "userMobile": tel,
            "address": address,
            "userWeightCount": weight,
            "userSendCount": number
        },
        dataType: 'json',
        type:"POST",
        success : function(response) {
            console.log(response);
        }
  })

controller代码:

@RequestMapping(value = "insert")
@ResponseBody
public Result<Boolean> insert(ProGroupUserRelVo vo) {
        Result<Boolean> result = new Result<>(false);
        System.out.println(vo);
        return result;
 }

经过不断的尝试,发现问题出在ajax的请求头:’Content-type’: ‘application/json; charset=utf-8’,这个参数设置指定了传到后台的参数类型为json格式,但是ajax传输的却不是json串,所以需要改成如下:

一、解决方法1

1.将ajax请求中的data转换成json字符串,采用JSON.stringify(s)函数完成转换

$.ajax({
        headers: {
            'Content-type': 'application/json; charset=utf-8'
        },
        url : getContextPath()+"/groupUserRel/insert",
        data : JSON.stringify({
            "groupId": "80901",
            "userName": name,
            "userMobile": tel,
            "address": address,
            "userWeightCount": weight,
            "userSendCount": number
        }),
        dataType: 'json',
        type:"POST",
        success : function(response) {
            console.log(response);
        }
  })

2.后台代码在接收参数对象上加上@RequestBody注解

@RequestMapping(value = "insert")
@ResponseBody
public Result<Boolean> insert(@RequestBody ProGroupUserRelVo vo) {
        Result<Boolean> result = new Result<>(false);
        System.out.println(vo);
        return result;
 }

这样就可以映射到参数了

二、解决方法2

直接将ajax请求头中的Content-type去除就可以了,让ajax发送默认的Content-Type: application/x-www-form-urlencoded,这样springmvc就可以自己解析,而不用告诉springmvc要以什么样的方式解析

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值