Spring3 MVC 使用JSON进行前后台数据交互

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@RequestMapping (value = "/list" , method = RequestMethod.GET)
@ResponseBody
public 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中配置:

1
2
3
4
5
6
7
8
9
< 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中接受参数也非常简单:

1
2
3
4
5
6
7
8
9
10
11
@RequestMapping (value= "/{id}" ,method=RequestMethod.GET)
@ResponseBody
public 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 的用户数据。

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

1
2
3
4
5
6
7
8
9
10
@RequestMapping (value= "/add" ,method=RequestMethod.POST)
@ResponseBody
public 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对象:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$.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 的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
  * @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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值