发布于 2017-02-25 12:07:05 | 258 次阅读 | 评论: 0 | 来源: 网友投递
Spring Framework 开源j2ee框架
Spring是什么呢?首先它是一个开源的项目,而且目前非常活跃;它是一个基于IOC和AOP的构架多层j2ee系统的框架,但它不强迫你必须在每一层 中必须使用Spring,因为它模块化的很好,允许你根据自己的需要选择使用它的某一个模块;它实现了很优雅的MVC,对不同的数据访问技术提供了统一的接口,采用IOC使得可以很容易的实现bean的装配,提供了简洁的AOP并据此实现Transcation Managment,等等
本文通过代码实例介绍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数据的相关资料,希望大家喜欢。