首页 技术 正文
技术 2022年11月7日
0 收藏 585 点赞 438 浏览 3556 个字

http://wbj0110.iteye.com/blog/2007918

在 Spring3 中,响应、接受 JSON都十分方便。
向前台返回 JSON 格式的数据:

12345678910111213141516 @RequestMapping(value = "/list", method = RequestMethod.GET)@ResponseBodypublic Map<String, Object> getUserList() {    logger.info("列表");    List<UserModel> list = new ArrayList<UserModel>();    UserModel um = new UserModel();    um.setId("1");    um.setUsername("sss");    um.setAge(222);    list.add(um);    Map<String, Object> modelMap = new     HashMap<String, Object>(3);    modelMap.put("total", "1");    modelMap.put("data", list);    modelMap.put("success", "true");    return modelMap;}

使用注解@ResponseBody可以将结果(一个包含字符串和JavaBean的Map),转换成JSON。
Spring这个转换是靠org.codehaus.jackson这个组件来实现的,所有需要引入jackson-core-asl和org.codehaus.jackson两个jar包,并且在web.xml中配置:

123456789 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">    <property name="messageConverters">        <util:list id="beanList">            <ref bean="mappingJacksonHttpMessageConverter" />        </util:list>    </property></bean> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />

在Controller中接受参数也非常简单:

1234567891011 @RequestMapping(value="/{id}",method=RequestMethod.GET)@ResponseBodypublic UserModel getUserById(@PathVariable String id){    logger.info("取值");    UserModel um = new UserModel();    um.setId(id);    um.setUsername("sss");    um.setAge(222);    return um;}

这样,可以访问类似于 http://localhost:8080/demo/user/1.do 来获取 id 为 1 的用户数据。

另外,在前台表单中向后台提交数据也非常方便:

12345678910 @RequestMapping(value="/add",method=RequestMethod.POST)@ResponseBodypublic Map<String, String> addUser(@RequestBody UserModel model){    logger.info("新增");    logger.info("捕获到前台传递过来的Model,名称为:"+model.getUsername());    Map<String, String> map = new HashMap<String, String>(1);    map.put("success", "true");    return map;}

使用 @RequestBody 注解前台只需要向 Controller 提交一段符合格式的 JSON,Spring 会自动将其拼装成 bean。

这样,Controller可以返回给前台JSON,也可以接收JSON。
而在前台,我们可以用 jQuery 来处理 JSON。
从这里,我得到了一个 jQuery 的插件,可以将一个表单的数据返回成JSON对象:

12345678910111213141516 $.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 的代码:

1234567891011121314151617181920212223242526272829303132333435363738394041 /** * @author liuweifeng */$(document).ready(function(){    jQuery.ajax({        type: 'GET',        contentType: 'application/json',        url: 'list.do',        dataType: 'json',        success: function(data){            if (data && data.success == "true") {                $('#info').html("共" + data.total + "条数据。<br/>");                $.each(data.data, function(i, item){                    $('#info').append("编号:" + item.id + ",姓名:" + item.username +                    ",年龄:" +                    item.age);                });            }        },        error: function(){            alert("error")        }    });    $("#submit").click(function(){        var jsonuserinfo = $.toJSON($('#form').serializeObject());        alert(jsonuserinfo);        jQuery.ajax({            type: 'POST',            contentType: 'application/json',            url: 'add.do',            data: jsonuserinfo,            dataType: 'json',            success: function(data){                alert("新增成功!");            },            error: function(){                alert("error")            }        });    });});

代码下载:http://www.box.net/shared/ia6qht3hfu

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,488
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,736
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,487
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,127
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,289