spring mvc 接收json

接收JSON
使用 @RequestBody 注解前台只需要向 Controller 提交一段符合格式的 JSON,Spring 会自动将其拼装成 bean。
1)在上面的项目中使用第一种方式处理返回JSON的基础上,增加如下方法:
Java代码 收藏代码

@RequestMapping(value="/add",method=RequestMethod.POST, headers = {"content-type=application/json","content-type=application/xml"})
@ResponseBody
public Object addUser(@RequestBody User user)
{
System.out.println(user.getName() + " " + user.getAge());
return new HashMap<String, String>().put("success", "true");
}

这里的POJO如下:
Java代码 收藏代码

public class User {
private String name;
private String age;

//getter setter
}


2)而在前台,我们可以用 jQuery 来处理 JSON。从这里,我得到了一个 jQuery 的插件,可以将一个表单的数据返回成JSON对象:
Js代码 收藏代码

$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function(){
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
}
else {
o[this.name] = this.value || '';
}
});
return o;
};


以下是使用 jQuery 接收、发送 JSON 的代码:
Js代码 收藏代码

$(document).ready(function(){
jQuery.ajax({
type: 'GET',
contentType: 'application/json',
url: 'jsonfeed.do',
dataType: 'json',
success: function(data){
if (data && data.status == "0") {
$.each(data.data, function(i, item){
$('#info').append("姓名:" + item.name +",年龄:" +item.age);
});
}
},
error: function(){
alert("error")
}
});
$("#submit").click(function(){
var jsonuserinfo = $.toJSON($('#form').serializeObject());
jQuery.ajax({
type: 'POST',
contentType: 'application/json',
url: 'add.do',
data: jsonuserinfo,
dataType: 'json',
success: function(data){
alert("新增成功!");
},
error: function(){
alert("error")
}
});
});
});


但是似乎用Spring这套东西真是个麻烦的事情,相对Jersey对RESTful的实现来看,确实有很多不简洁的地方。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值