Spring MVC 3.0 RestTemplate


跟隨 Web Service 一路走來, 記憶中的 Apache SOAP, Apache Axis, XFire, 標准化的JAX-RPC, JAX-WS, 到后來半路殺出的的 Spring-WS, CXF
一切剛剛開始,一切望塵莫及,短命是純技術的特征。
RPC 的平台局限性,SOAP 的類型 bind 的易脆性, JAX-WS 工具的信賴度, Spring-WS contract first 使一個小時可以完成(甚至在IDE中十分鍾可以完成)的工作,要整一天,還要到看到 JUnit 的 Green bar 才算數。

已經標准化的JAX-RS,證明 RESTful 已經成為SOA加架的主流,以至於 Spring-WS 停止在了他的 1.59 版本,SpringSource 放棄了這個市場么?

呵呵!它早已意識到了問題的所在,市場上有多少 Spring-WS 的需求? 相比於它的 IoC, Spring-WS 是個失敗的產品。它已經轉移了重點:


2.5.6.1 Comprehensive REST support

Server-side support for building RESTful applications has been provided as an extension of the existing annotation driven MVC web framework. Client-side support is provided by the RestTemplate class in the spirit of other template classes such as JdbcTemplate and JmsTemplate. Both server and client side REST functionality make use of HttpConverters to facilitate the conversion between objects and their representation in HTTP requests and responses.

The MarshallingHttpMessageConverter uses the Object to XML mapping functionality mentioned earlier.
 

下面的代碼 使用 RestTemplate 訪問,SpringMVC 3 的一個 Controller (RESTful service),service 要求一個 SHA512 key.

RestTemplate 封裝了一個 ClientHttpRequestFactory,Spring3 提供兩種實現:

1. SimpleClientHttpRequestFactory 采用JDK URLConnection

2. CommonsClientHttpRequestFactory 采用 commons/httpclient 3.x (注意不是4)

Java代碼    收藏代碼
  1. @SuppressWarnings("unchecked")  
  2. private List<BufferedImage> searchProductImage(String keyword, String apikey, int page, int max) {  
  3.   
  4.     final String restUri = "http://localhost:8080/hjpetstore/rest/products/{keyword}?apikey={apikey}&page={page}&max={max}";  
  5.   
  6.     Source product = restTemplate.getForObject(restUri, Source.class, keyword, apikey, page, max);  
  7.   
  8.     final String imageUrl = "http://localhost:8080/hjpetstore/images/{imageFileName}";  
  9.   
  10.     List<BufferedImage> images = (List<BufferedImage>) xpathTemplate.evaluate("//image", product, new NodeMapper() {  
  11.   
  12.         @Override  
  13.         public Object mapNode(Node node, int i) throws DOMException {  
  14.             //Element image = (Element) node;  
  15.             org.jdom.Element image = new DOMBuilder().build((Element) node);  
  16.             String imageFileName = image.getValue();  
  17.             //String imageFileName = image.getFirstChild().getNodeValue();  
  18.   
  19.             return restTemplate.getForObject(imageUrl, BufferedImage.class, imageFileName);  
  20.         }  
  21.     });  
  22.   
  23.     return images;  
  24. }  



邏輯的處理是 Xpath 解析 Response的XML,再次 請求 image 的url,然后利用  org.springframework.http.converter.BufferedImageHttpMessageConverter 返回一個 BufferedImage 的列表,送給 Swing 組件渲染出來。

 

Xml代碼    收藏代碼
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xmlns:p="http://www.springframework.org/schema/p"  
  5.        xmlns:aop="http://www.springframework.org/schema/aop"  
  6.        xmlns:tx="http://www.springframework.org/schema/tx"  
  7.        xmlns:util="http://www.springframework.org/schema/util"  
  8.        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  9.        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
  10.        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  11.        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">  
  12.   
  13.     <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  14.         <property name="locations">  
  15.             <list>  
  16.                 <value>application.properties</value>  
  17.             </list>  
  18.         </property>  
  19.     </bean>  
  20.   
  21.     <bean id="searchProductListRest" class="org.pprun.hjpetstore.client.SearchProductListRest">  
  22.         <constructor-arg ref="restTemplate"/>  
  23.         <constructor-arg ref="xpathTemplate"/>  
  24.     </bean>  
  25.   
  26.   
  27.     <!-- the template can be used to call home-grown or external RESTful service -->  
  28.   
  29.     <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">  
  30.         <property name="requestFactory">  
  31.             <bean class="org.springframework.http.client.CommonsClientHttpRequestFactory">  
  32.                 <constructor-arg>  
  33.                     <bean class="org.apache.commons.httpclient.HttpClient">  
  34.                         <constructor-arg index="0">  
  35.                             <bean id="httpClientParams" class="org.apache.commons.httpclient.params.HttpClientParams">  
  36.                                 <property name="authenticationPreemptive" value="true"/>  
  37.                             </bean>  
  38.                         </constructor-arg>  
  39.                         <constructor-arg index="1">  
  40.                             <bean class="org.apache.commons.httpclient.MultiThreadedHttpConnectionManager">  
  41.                                 <property name="params">  
  42.                                     <bean class="org.apache.commons.httpclient.params.HttpConnectionManagerParams">  
  43.                                         <property name="soTimeout" value="${rest.service.timeout}" />  
  44.                                         <property name="connectionTimeout" value="${rest.service.connectionTimeout}" />  
  45.                                         <property name="defaultMaxConnectionsPerHost" value="${rest.service.maxConnections}" />  
  46.                                         <property name="maxTotalConnections" value="${rest.service.maxTotalConnections}" />  
  47.                                         <property name="staleCheckingEnabled" value="${rest.service.staleCheckEnabled}" />  
  48.                                     </bean>  
  49.                                 </property>  
  50.                             </bean>  
  51.                         </constructor-arg>  
  52.                     </bean>  
  53.                 </constructor-arg>  
  54.             </bean>  
  55.         </property>  
  56.         <!-- 19.9.2 HTTP Message Conversion  
  57.             several main media type converters have been registered,  
  58.             but if we overwrite tihs property, we have to list all our need  
  59.         -->  
  60.         <property name="messageConverters">  
  61.             <list>  
  62.                 <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>  
  63.                 <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>  
  64.             </list>  
  65.         </property>  
  66.     </bean>  
  67.   
  68.     <bean id="xpathTemplate" class="org.springframework.xml.xpath.Jaxp13XPathTemplate"/>  
  69.       
  70. </beans>  
 


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM