SpringMVC学习--json

  • 简介

  json数据格式在接口调用中、html页面中较常用,json格式比较简单,解析还比较方便。比如:webservice接口,传输json数据。

  • springmvc与json交互

  • @RequestBody和@ResponseBody

 

     @RequestBody

  作用:

  @RequestBody注解用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口将读到的内容转换为jsonxml等格式的数据并绑定到controller方法的参数上。

  @ResponseBody

 

  作用:

 

  该注解用于将Controller的方法返回的对象,通过HttpMessageConverter接口转换为指定格式的数据如:json,xml等,通过Response响应给客户端。

 

  • 请求json,响应json实现

  1、环境准备

  Springmvc默认用MappingJacksonHttpMessageConverter对json数据进行转换,需要加入jackson的包,如下:

 

  2、配置json转换器

 

  在注解适配器中加入messageConverters

 

1 <!--注解适配器 -->
2     <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
3         <property name="messageConverters">
4         <list>
5         <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
6         </list>
7         </property>
8     </bean>

 

  注意:如果使用<mvc:annotation-driven /> 则不用定义上边的内容。

  3、controller编写

 

1 // 商品修改提交json信息,响应json信息
2     @RequestMapping("/editItemSubmit_RequestJson")
3     public @ResponseBody Items editItemSubmit_RequestJson(@RequestBody Items items) throws Exception {
4         System.out.println(items);
5         //itemService.saveItem(items);
6         return items;
7 
8     }

 

  4、页面js的编写

 1 function request_json(){
 2         $.ajax({
 3             type:"post",
 4             url:"${pageContext.request.contextPath }/item/editItemSubmit_RequestJson.action",
 5             contentType:"application/json;charset=utf-8",
 6             data:'{"name":"测试商品","price":99.9}',
 7             success:function(data){
 8                 alert(data);
 9             }
10         });
11     }

  5、请key/value,响应json实现

 

  表单默认请求application/x-www-form-urlencoded格式的数据即key/value,通常有postget两种方法,响应json数据是为了方便客户端处理,实现如下:

 

  controller编写:

 

1 // 商品修改提交,提交普通form表单数据,响应json
2     @RequestMapping("/editItemSubmit_ResponseJson")
3     public @ResponseBody Items editItemSubmit_ResponseJson(Items items) throws Exception {
4 
5         System.out.println(items);
6 
7 //        itemService.saveItem(items);
8         return items;
9     }

 

  页面js方法编写

 

 1 function formsubmit(){
 2     var user = " name=测试商品&price=99.9";
 3     alert(user);
 4       $.ajax(
 5         {
 6             type:'post',//这里改为get也可以正常执行
 7             url:'${pageContext.request.contextPath}/item/ editItemSubmit_RequestJson.action',
 8 //ContentType没指定将默认为:application/x-www-form-urlencoded
 9             data:user,
10             success:function(data){
11                 alert(data.name);
12             }
13             
14         }    
15     )
16 }

 

  • 小结

  实际开发中常用第二种方法,请求key/value数据,响应json结果,方便客户端对结果进行解析。另外,也可以和一些前段框架(如:ExtJS)结合使用,因为前端框架就是键值对的解析。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2016-06-21 20:25  ngulc  阅读(469)  评论(0编辑  收藏  举报