`

Spring RESTful服务接收和返回JSON最佳实践

阅读更多

返回JSON

1) 用Maven构建web项目:

构建过程参考limingnihao的blog(写得相当的详细!!!):使用Eclipse构建Maven的SpringMVC项目

注解@ResponseBody可以将结果(一个包含字符串和JavaBean的Map),转换成JSON。由于Spring是采用对JSON进行了封装的jackson来生成JSON和返回给客户端,所以这里需要添加jackson的相关包。项目的pom.xml配置如下:

Xml代码   收藏代码
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  3.     <modelVersion>4.0.0</modelVersion>  
  4.     <groupId>com.watson</groupId>  
  5.     <artifactId>rest-spring</artifactId>  
  6.     <packaging>war</packaging>  
  7.     <version>0.0.1-SNAPSHOT</version>  
  8.     <name>rest-spring Maven Webapp</name>  
  9.     <url>http://maven.apache.org</url>  
  10.       
  11.     <dependencies>  
  12.         <!-- 省略其他配置,具体可以参考附件-->  
  13.         ......  
  14.         <dependency>  
  15.             <groupId>org.codehaus.jackson</groupId>  
  16.             <artifactId>jackson-mapper-asl</artifactId>  
  17.             <version>1.4.2</version>  
  18.         </dependency>  
  19.         <dependency>  
  20.             <groupId>org.codehaus.jackson</groupId>  
  21.             <artifactId>jackson-core-asl</artifactId>  
  22.             <version>1.4.2</version>  
  23.         </dependency>  
  24.     </dependencies>  
  25. </project>  

  

2) 在web.xml配置Spring的请求处理的Servlet,具体设置:

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  5.     version="2.5">  
  6.   
  7.     <display-name>Spring-Rest</display-name>  
  8.     <servlet>  
  9.         <servlet-name>rest</servlet-name>  
  10.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  11.         <init-param>  
  12.             <param-name>contextConfigLocation</param-name>  
  13.             <param-value>/WEB-INF/rest-servlet.xml</param-value>  
  14.         </init-param>  
  15.         <load-on-startup>1</load-on-startup>  
  16.     </servlet>  
  17.   
  18.     <servlet-mapping>  
  19.         <servlet-name>rest</servlet-name>  
  20.         <url-pattern>/</url-pattern>  
  21.     </servlet-mapping>  
  22. </web-app>  

 

3) 在rest-servlet.xml中配置如下:

Xml代码   收藏代码
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:context="http://www.springframework.org/schema/context"  
  3.     xmlns:mvc="http://www.springframework.org/schema/mvc"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xsi:schemaLocation="  
  6.         http://www.springframework.org/schema/beans       
  7.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  8.         http://www.springframework.org/schema/context   
  9.         http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  10.         http://www.springframework.org/schema/mvc  
  11.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  
  12.    
  13.     <context:component-scan base-package="com.mkyong.common.controller" />  
  14.     <mvc:annotation-driven />  
  15.   
  16. </beans>  

 

   为了解决乱码问题,需要添加如下配置,并且这里可以显示的添加MappingJacksonHttpMessageConverter这个转换器。

Xml代码   收藏代码
  1. <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
  2.     <property name="messageConverters">  
  3.         <list>  
  4.             <bean class="org.springframework.http.converter.StringHttpMessageConverter">  
  5.                 <property name="supportedMediaTypes">  
  6.                     <list>  
  7.                         <value>text/plain;charset=UTF-8</value>  
  8.                     </list>  
  9.                 </property>  
  10.             </bean>  
  11.             <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />  
  12.         </list>  
  13.     </property>  
  14. </bean>  

 

 

4) 编写自己的服务组件类,使用MVC的annotation风格,使用 @ResponseBody处理返回值。具体代码如下:

Java代码   收藏代码
  1. @RequestMapping("/jsonfeed")  
  2. public @ResponseBody Object getJSON(Model model) {  
  3.     List<TournamentContent> tournamentList = new ArrayList<TournamentContent>();  
  4.     tournamentList.add(TournamentContent.generateContent("FIFA"new Date(), "World Cup""www.fifa.com/worldcup/"));  
  5.     tournamentList.add(TournamentContent.generateContent("FIFA"new Date(), "U-20 World Cup""www.fifa.com/u20worldcup/"));  
  6.     tournamentList.add(TournamentContent.generateContent("FIFA"new Date(), "U-17 World Cup""www.fifa.com/u17worldcup/"));  
  7.     tournamentList.add(TournamentContent.generateContent("中超"new Date(), "中超""www.fifa.com/confederationscup/"));  
  8.     model.addAttribute("items", tournamentList);  
  9.     model.addAttribute("status"0);  
  10.       
  11.     return model;  
  12. }  

 

 5)将运行项目,在浏览器中输入http://[host]:[port]/[appname]/jsonfeed.json,例如楼主的实例中输入如下:http://localhost:7070/rest-spring/jsonfeed/,得到结果为:

Json代码   收藏代码
  1. {"status":0,"items":[{"name":"World Cup","id":8,"link":"www.fifa.com/worldcup/","author":"FIFA","publicationDate":1334559460940},{"name":"U-20 World Cup","id":9,"link":"www.fifa.com/u20worldcup/","author":"FIFA","publicationDate":1334559460940},{"name":"U-17 World Cup","id":10,"link":"www.fifa.com/u17worldcup/","author":"FIFA","publicationDate":1334559460940},{"name":"Confederations Cup","id":11,"link":"www.fifa.com/confederationscup/","author":"FIFA","publicationDate":1334559460940}]}  

 

这里我们也可以利用Spring3MVC中对试图和内容协商的方法来处理返回JSON的情况,下面步骤接上面第2步:

3) 在rest-servlet.xml中对相关进行具体的设置:

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"  
  5.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/aop   
  7.         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
  8.         http://www.springframework.org/schema/beans   
  9.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  10.         http://www.springframework.org/schema/context   
  11.         http://www.springframework.org/schema/context/spring-context-3.0.xsd   
  12.         http://www.springframework.org/schema/mvc   
  13.         http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd   
  14.         http://www.springframework.org/schema/tx   
  15.         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">  
  16.   
  17.     <!-- 自动搜索@Controller标注的类,包括其下面的子包 -->  
  18.     <context:component-scan base-package="com.watson.rest" />  
  19.   
  20.     <!-- 根据客户端的不同的请求决定不同的view进行响应, 如 /blog/1.json /blog/1.xml -->  
  21.     <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">  
  22.         <!-- 设置为true以忽略对Accept Header的支持 -->  
  23.         <property name="ignoreAcceptHeader" value="true" />  
  24.           
  25.         <!-- 在没有扩展名时即: "/blog/1" 时的默认展现形式 -->  
  26.         <property name="defaultContentType" value="text/html" />  
  27.   
  28.         <!-- 扩展名至mimeType的映射,即 /blog.json => application/json -->  
  29.         <property name="mediaTypes">  
  30.             <map>  
  31.                 <entry key="html" value="text/html" />  
  32.                 <entry key="pdf" value="application/pdf" />  
  33.                 <entry key="xsl" value="application/vnd.ms-excel" />  
  34.                 <entry key="xml" value="application/xml" />  
  35.                 <entry key="json" value="application/json" />  
  36.             </map>  
  37.         </property>  
  38.       
  39.         <!-- 用于开启 /blog/123?format=json 的支持 -->  
  40.         <property name="favorParameter" value="false" />  
  41.         <property name="viewResolvers">  
  42.             <list>  
  43.                 <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />  
  44.                 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  45.                     <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />  
  46.                     <property name="prefix" value="/pages" />  
  47.                     <property name="suffix" value=".jsp"></property>  
  48.                 </bean>  
  49.             </list>  
  50.         </property>  
  51.         <property name="defaultViews">  
  52.             <list>  
  53.                 <!-- for application/json -->  
  54.                 <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />  
  55.                 <!-- for application/xml -->  
  56.                 <!--   
  57.                 <bean class="org.springframework.web.servlet.view.xml.MarshallingView">   
  58.                     <property name="marshaller">   
  59.                         <bean class="org.springframework.oxm.xstream.XStreamMarshaller"/>   
  60.                     </property>   
  61.                 </bean>   
  62.                 -->  
  63.             </list>  
  64.         </property>  
  65.     </bean>  
  66. </beans>  
 
 4)编写自己的服务组件类,使用MVC的annotation风格,这里可以不再使用@ResponseBody断言。具体代码如下:
Java代码   收藏代码
  1. //FINAL   
  2. package com.watson.rest.json;  
  3.   
  4. import org.springframework.stereotype.Controller;  
  5. import org.springframework.ui.Model;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7.   
  8. import com.watson.rest.feeds.TournamentContent;  
  9.   
  10. import java.util.ArrayList;  
  11. import java.util.Date;  
  12. import java.util.List;  
  13.   
  14.   
  15. @Controller  
  16. public class FeedController {  
  17.     @RequestMapping("/jsonfeed")  
  18.     public String getJSON(Model model) {  
  19.         List<TournamentContent> tournamentList = new ArrayList<TournamentContent>();  
  20.         tournamentList.add(TournamentContent.generateContent("FIFA"new Date(), "World Cup""www.fifa.com/worldcup/"));  
  21.         tournamentList.add(TournamentContent.generateContent("FIFA"new Date(), "U-20 World Cup""www.fifa.com/u20worldcup/"));  
  22.         tournamentList.add(TournamentContent.generateContent("FIFA"new Date(), "U-17 World Cup""www.fifa.com/u17worldcup/"));  
  23.         tournamentList.add(TournamentContent.generateContent("FIFA"new Date(), "Confederations Cup""www.fifa.com/confederationscup/"));  
  24.         model.addAttribute("items", tournamentList);  
  25.         model.addAttribute("status"0);  
  26.         return "jsontournamenttemplate";  
  27.     }  
  28. }  
 
这里的TournamentContent是自定义的POJO类:
Java代码   收藏代码
  1. public class TournamentContent {  
  2.     private static int idCounter = 0;  
  3.     private String author;  
  4.     private Date publicationDate;  
  5.     private String name;  
  6.     private String link;  
  7.     private int id;  
  8.   
  9.     public static TournamentContent generateContent(String author, Date date, String name, String link) {  
  10.         TournamentContent content = new TournamentContent();  
  11.         content.author = author;  
  12.         content.publicationDate = date;  
  13.         content.name = name;  
  14.         content.link = link;  
  15.         content.id = idCounter++;  
  16.   
  17.         return content;  
  18.     }  
  19.       
  20.     //省略getter、setter  
  21. }  
 
5)将运行项目,在浏览器中输入http://[host]:[port]/[appname]/jsonfeed.json,例如楼主的实例中输入如下:http://localhost:7070/rest-spring/jsonfeed.json,得到结果为:
Json代码   收藏代码
  1. {"status":0,"items":[{"name":"World Cup","id":8,"link":"www.fifa.com/worldcup/","author":"FIFA","publicationDate":1334559460940},{"name":"U-20 World Cup","id":9,"link":"www.fifa.com/u20worldcup/","author":"FIFA","publicationDate":1334559460940},{"name":"U-17 World Cup","id":10,"link":"www.fifa.com/u17worldcup/","author":"FIFA","publicationDate":1334559460940},{"name":"Confederations Cup","id":11,"link":"www.fifa.com/confederationscup/","author":"FIFA","publicationDate":1334559460940}]}  
 
至此,Spring RESTful服务返回JSON的实践基本完成(因为这里对EXCEPTION的处理还够)。个人认为第一种方式更加适合一般的使用,特别是显示的添加MappingJacksonHttpMessageConverter这个转换器和对乱码的处理。
 
接收JSON
使用 @RequestBody 注解前台只需要向 Controller 提交一段符合格式的 JSON,Spring 会自动将其拼装成 bean。
1)在上面的项目中使用第一种方式处理返回JSON的基础上,增加如下方法:
Java代码   收藏代码
  1. @RequestMapping(value="/add",method=RequestMethod.POST)  
  2. @ResponseBody  
  3. public Object addUser(@RequestBody User user)  
  4. {  
  5.     System.out.println(user.getName() + " " + user.getAge());  
  6.     return new HashMap<String, String>().put("success""true");  
  7. }  
 这里的POJO如下:
Java代码   收藏代码
  1. public class User {  
  2.     private String name;  
  3.     private String age;  
  4.   
  5.     //getter setter  
  6. }  
 
2)而在前台,我们可以用 jQuery 来处理 JSON。从这里,我得到了一个 jQuery 的插件,可以将一个表单的数据返回成JSON对象:
Js代码   收藏代码
  1. $.fn.serializeObject = function(){  
  2.     var o = {};  
  3.     var a = this.serializeArray();  
  4.     $.each(a, function(){  
  5.         if (o[this.name]) {  
  6.             if (!o[this.name].push) {  
  7.                 o[this.name] = [o[this.name]];  
  8.             }  
  9.             o[this.name].push(this.value || '');  
  10.         }  
  11.         else {  
  12.             o[this.name] = this.value || '';  
  13.         }  
  14.     });  
  15.     return o;  
  16. };  
 
   以下是使用 jQuery 接收、发送 JSON 的代码:
Js代码   收藏代码
  1. $(document).ready(function(){  
  2.     jQuery.ajax({  
  3.         type: 'GET',  
  4.         contentType: 'application/json',  
  5.         url: 'jsonfeed.do',  
  6.         dataType: 'json',  
  7.         success: function(data){  
  8.             if (data && data.status == "0") {  
  9.                 $.each(data.data, function(i, item){  
  10.                     $('#info').append("姓名:" + item.name +",年龄:" +item.age);  
  11.                 });  
  12.             }  
  13.         },  
  14.         error: function(){  
  15.             alert("error")  
  16.         }  
  17.     });  
  18.     $("#submit").click(function(){  
  19.         var jsonuserinfo = $.toJSON($('#form').serializeObject());  
  20.         jQuery.ajax({  
  21.             type: 'POST',  
  22.             contentType: 'application/json',  
  23.             url: 'add.do',  
  24.             data: jsonuserinfo,  
  25.             dataType: 'json',  
  26.             success: function(data){  
  27.                 alert("新增成功!");  
  28.             },  
  29.             error: function(){  
  30.                 alert("error")  
  31.             }  
  32.         });  
  33.     });  
  34. });  
 
但是似乎用Spring这套东西真是个麻烦的事情,相对Jersey对RESTful的实现来看,确实有很多不简洁的地方。

 

 

参考:

官方文档:http://static.springsource.org/spring/docs/3.0.0.M3/spring-framework-reference/html/ch18.html

badqiu的BOLG: 《spring REST中的内容协商(同一资源,多种展现:xml,json,html)》

liuweifeng的BOLG http://blog.liuweifeng.net/archives/407

Gary Mark等的书籍:《Spring Recipes》2ed

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics