ajax向springmvc传递对象参数

58 篇文章 0 订阅
46 篇文章 0 订阅

我们在使用前端的ajax技术过程中,有的时候简简单单的向后台的springmvn传递参数,直接使用如下代码即可:(jquery的ajax代码)

var options = {
    url: 'helloworld',
    method: 'get',
    dataType: 'json',
    data: {
        teamId: 123
    },
    success: function (rs) {
        // code here
    },
    error: function (rs) {
        // code here
    }
};
$.ajax(options);

 后台springmvc代码:

@RequestMapping(value = { "/helloworld" }, method = { RequestMethod.GET })
@ResponseBody
public Boolean helloworld(@RequestParam("teamId") Long teamId)  {
    LOGGER.debug("start to helloworld. teamId:{}", teamId);
   
    Boolean rs = null; // coder here
    LOGGER.debug("finish helloworld. teamId:{}", teamId);
    return rs;
}

 上面也是常用的情况。

但是有的时候我们需要用ajax向后台传递对象,该如何做呢?前端传递的是JavaScript的对象,而后台接收的是java的对象。springmvn为我们做好了由JavaScript对象到Java对象的json转换。如下:

var paramsArr = [];
for(var i = 0; i < 10; i++) {
    var obj = {
        id: i,
        name: 'name-' + i
    };
    paramsArr.push(obj);
}

var options = {
    url: 'helloworld',
    method: 'post', // 注意这里,传递对象给后台,这里必须是 POST 否则无法将对象封装到POST的body中流
    dataType: 'json',
    contentType: 'application/json', // 注意这里,传递对象给后台,这里必须是 application/json
    data: JSON.stringify(paramsArr), // 注意这里,传递对象给后台,这里必须将对象进行序列化
    success: function (rs) {
        // code here
    },
    error: function (rs) {
        // code here
    }
};
$.ajax(options);

 

class Person {
    private Long id;
    private String name;
    // setter / getter here
}

/**
 * 
 *  注意参数中的 @RequestBody。 它将会读取POST请求中的body中的数据流,然后JSON反序列化为java的对象。
 */
@RequestMapping(value = { "/helloworld" }, method = { RequestMethod.POST })
@ResponseBody
public Boolean helloworld(@RequestBody List<Person> persons)  {
    LOGGER.debug("start to helloworld. persons:{}", persons);
   
    Boolean rs = null; // coder here
    LOGGER.debug("finish helloworld. persons:{}", persons);
    return rs;
}

这样对象参数就能传递给后台了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值