本文通過代碼實例介紹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的實現來看,確實有很多不簡潔的地方。
以上所述是本文給大家分享的Spring mvc 接收json數據的相關資料,希望大家喜歡。