1. 程式人生 > >Spring整合CXF webservice restful 例項

Spring整合CXF webservice restful 例項

webservice restful介面跟soap協議的介面實現大同小異,只是在提供服務的類/介面的註解上存在差異,具體看下面的程式碼,然後自己對比下就可以了。

用到的基礎類

User.java

[原始碼]
  1.  @XmlRootElement(name="User")  
  2.  publicclass User {  
  3.      private String userName;  
  4.      private String sex;  
  5.      private int age;  
  6.      public User(String userName, String sex, int age) {  
  7.          super();  
  8.          this.userName = userName;  
  9.          this.sex = sex;  
  10.          this.age = age;  
  11.      }  
  12.      public User() {  
  13.          super();  
  14.      }  
  15.      public String getUserName() {  
  16.          return userName;  
  17.      }  
  18.      public void setUserName(String userName) {  
  19.          this.userName = userName;  
  20.      }  
  21.      public String getSex() {  
  22.          return sex;  
  23.      }  
  24.      public void setSex(String sex) {  
  25.          this.sex = sex;  
  26.      }  
  27.      public int getAge() {  
  28.          return age;  
  29.      }  
  30.      public void setAge(int age) {  
  31.          this.age = age;  
  32.      }  
  33.      publicstatic
     void main(String[] args) throws IOException {  
  34.          System.setProperty("http.proxySet""true");   
  35.          System.setProperty("http.proxyHost",  "192.168.1.20");   
  36.          System.setProperty("http.proxyPort""8080");  
  37.          URL url = new URL("http://www.baidu.com");   
  38.          URLConnection con =url.openConnection();   
  39.          System.out.println(con);  
  40.      }  
  41.  }  

接下來是服務提供類,PhopuRestfulService.java

[原始碼]
  1.  @Path("/phopuService")  
  2.  publicclass PhopuRestfulService {  
  3.      Logger logger = Logger.getLogger(PhopuRestfulServiceImpl.class);  
  4.      @GET  
  5.      @Produces(MediaType.APPLICATION_JSON) //指定返回資料的型別 json字串
  6.      //@Consumes(MediaType.TEXT_PLAIN) //指定請求資料的型別 文字字串
  7.      @Path("/getUser/{userId}")  
  8.      public User getUser(@PathParam("userId")String userId) {  
  9.          this.logger.info("Call getUser() method...."+userId);  
  10.          User user = new User();  
  11.          user.setUserName("中文");  
  12.          user.setAge(26);  
  13.          user.setSex("m");  
  14.          return user;  
  15.      }  
  16.      @POST  
  17.      @Produces(MediaType.APPLICATION_JSON) //指定返回資料的型別 json字串
  18.      //@Consumes(MediaType.TEXT_PLAIN) //指定請求資料的型別 文字字串
  19.      @Path("/getUserPost")  
  20.      public User getUserPost(String userId) {  
  21.          this.logger.info("Call getUserPost() method...."+userId);  
  22.          User user = new User();  
  23.          user.setUserName("中文");  
  24.          user.setAge(26);  
  25.          user.setSex("m");  
  26.          return user;  
  27.      }  
  28.  }  

web.xml配置,跟soap協議的介面一樣

[原始碼]
  1.  <!-- CXF webservice 配置 -->  
  2.      <servlet>  
  3.          <servlet-name>cxf-phopu</servlet-name>  
  4.          <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>  
  5.      </servlet>  
  6.      <servlet-mapping>  
  7.          <servlet-name>cxf-phopu</servlet-name>  
  8.          <url-pattern>/services/*</url-pattern>  
  9.      </servlet-mapping>  

Spring整合配置

[原始碼]
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:p="http://www.springframework.org/schema/p"
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5.     xmlns:jaxws="http://cxf.apache.org/jaxws"
  6.     xmlns:jaxrs="http://cxf.apache.org/jaxrs"
  7.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  8.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  9.         http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
  10.         http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
  11.     <import resource="classpath:/META-INF/cxf/cxf.xml" />  
  12.     <import resource="classpath:/META-INF/cxf/cxf-servlet.xml" />  
  13.     <import resource="classpath:/META-INF/cxf/cxf-extension-soap.xml" />  
  14.     <!-- 配置restful json 解析器 , 用CXF自帶的JSONProvider需要注意以下幾點  
  15.     -1、dropRootElement 預設為false,則Json格式會將類名作為第一個節點,如{Customer:{"id":123,"name":"John"}},如果配置為true,則Json格式為{"id":123,"name":"John"}。  
  16.     -2、dropCollectionWrapperElement屬性預設為false,則當遇到Collection時,Json會在集合中將容器中類名作為一個節點,比如{"Customer":{{"id":123,"name":"John"}}},而設定為false,則JSon格式為{{"id":123,"name":"John"}}  
  17.     -3、serializeAsArray屬性預設為false,則當遇到Collecion時,格式為{{"id":123,"name":"John"}},如果設定為true,則格式為[{"id":123,"name":"john"}],而Gson等解析為後者  
  18.     <bean id="jsonProviders"class="org.apache.cxf.jaxrs.provider.json.JSONProvider">  
  19.         <property name="dropRootElement" value="true" />  
  20.         <property name="dropCollectionWrapperElement" value="true" />  
  21.         <property name="serializeAsArray" value="true" />  
  22.     </bean>  
  23.  -->  
  24.     <!-- 服務類 -->  
  25.     <bean id="phopuService"class="com.phopu.service.PhopuRestfulService" />  
  26.     <jaxrs:server id="service"  address="/">  
  27.         <jaxrs:inInterceptors>  
  28.             <bean class="org.apache.cxf.interceptor.LoggingInInterceptor" />  
  29.         </jaxrs:inInterceptors>  
  30.         <!--serviceBeans:暴露的WebService服務類-->  
  31.         <jaxrs:serviceBeans>  
  32.             <ref bean="phopuService" />  
  33.         </jaxrs:serviceBeans>  
  34.         <!--支援的協議-->  
  35.         <jaxrs:extensionMappings>  
  36.             <entry key="json" value="application/json"/>  
  37.             <entry key="xml" value="application/xml" />  
  38.             <entry key="text" value="text/plain" />  
  39.         </jaxrs:extensionMappings>  
  40.         <!--物件轉換-->  
  41.         <jaxrs:providers>  
  42.             <!-- <ref bean="jsonProviders" /> 這個地方直接用CXF的物件轉換器會存在問題,當介面釋出,第一次訪問沒問題,但是在訪問服務就會報錯,等後續在研究下 -->  
  43.             <bean class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider" />  
  44.         </jaxrs:providers>  
  45.     </jaxrs:server>  
  46. </beans>  

客戶端呼叫示例:

對於get方式的服務,直接在瀏覽器中輸入 http://localhost:8080/phopu/services/phopuService/getUser/101010500 就可以直接看到返回的json字串 

[原始碼]
  1. {"userName":"中文","sex":"m","age":26}  

客戶端呼叫程式碼如下:

[原始碼]
  1. publicstatic void getWeatherPostTest() throws Exception{  
  2.          String url = "http://localhost:8080/phopu/services/phopuService/getUserPost";  
  3.          HttpClient httpClient = HttpClients.createSystem();  
  4.          //HttpGet httpGet = new HttpGet(url);  //介面get請求,post not allowed
  5.          HttpPost httpPost = new HttpPost(url);  
  6.          httpPost.addHeader(CONTENT_TYPE_NAME, "text/plain");  
  7.          StringEntity se = new StringEntity("101010500");  
  8.          se.setContentType("text/plain");  
  9.          httpPost.setEntity(se);  
  10.          HttpResponse response = httpClient.execute(httpPost);  
  11.          int status = response.getStatusLine().getStatusCode();  
  12.          log.info("[介面返回狀態嗎] : " + status);  
  13.          String weatherInfo = ClientUtil.getReturnStr(response);  
  14.          log.info("[介面返回資訊] : " + weatherInfo);  
  15.      }  

客戶端呼叫返回資訊如下:

ClientUtil類是我自己封裝的一個讀取response返回資訊的類,encoding是UTF-8

[原始碼]
  1. publicstatic String getReturnStr(HttpResponse response) throws Exception {  
  2.          String result = null;  
  3.          BufferedInputStream buffer = new BufferedInputStream(response.getEntity().getContent());  
  4.          byte[] bytes = new byte[1024];  
  5.          int line = 0;  
  6.          StringBuilder builder = new StringBuilder();  
  7.          while ((line = buffer.read(bytes)) != -1) {  
  8.              builder.append(new String(bytes, 0, line, HTTP_SERVER_ENCODING));  
  9.          }  
  10.          result = builder.toString();  
  11.          return result;  
  12.      }  

相關推薦

Spring整合CXF webservice restful 例項

webservice restful介面跟soap協議的介面實現大同小異,只是在提供服務的類/介面的註解上存在差異,具體看下面的程式碼,然後自己對比下就可以了。 用到的基礎類 User.java [原始碼]  @XmlRootElement(name="U

Spring整合cxf搭建webservice【一、服務端】

1、匯入jar包(普通web專案) 引入依賴(maven專案) <!-- webservice依賴框架CXF --> <dependency> <groupId>org.apache.cxf</groupId>

maven整合CXF WebService+Spring @Resource無法注入問題解決方法

筆者是一個出道不長的小碼農.工作中需要用的maven 結合jetty容器進行開發的前提背景下 廢話不多說直接上程式碼 更改前的web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns=

在java中使用spring整合cxf實現webservice

在java中實現webservice有兩種常用的方式,一種是cxf,另一種是axis。這兩種方式的區別大家可以自己在網上找找參考一下。cxf可以與spring進行整合,是一款不錯的webservice產品。今天給大家講解一下使用spring整合cxf實現we

Spring boot 整合CXF webservice遇到的一些問題及解決,

在spring boot整合CXF開發是遇到的一些問題    以及整合方式整合過程    網上資料引入cxf-spring-boot-starter-jaxws依賴即可<dependency> <groupId>org.apache.cxf&l

axis2+spring整合釋出webservice服務

1.環境搭建,準備相應環境jar包    axis2-1.6.0.0下載地址: http://axis.apache.org/axis2/java/core/download.cgi    spring相關jar包下載地址

Spring 整合CXF需要的配置及處理步驟

CXF配置 1.web.xml 配置 <!--Spring MVC是通過DispatcherServlet來載入Spring配置檔案的,因此不需要在web.xml中配置ContextLoaderListener。 但是CXF卻需要通過ContextLoaderLis

activiti自定義流程之Spring整合activiti-modeler5.16例項(六):啟動流程

1.啟動流程並分配任務是單個流程的正式開始,因此要使用到runtimeService介面,以及相關的啟動流程的方法。我習慣於用流程定義的key啟動,因為有多個版本的流程定義時,用key啟動預設會使用最新版本。同時,因為啟動中查詢了流程部署時xml檔案中流程節點的資訊,也用

spring 整合CXF框架拋異常

Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListenerorg.springframework.beans.fa

activiti自定義流程之Spring整合activiti-modeler5.16例項(二):建立流程模型

1.maven導包,這裡就沒有什麼多的好說了,直接程式碼: <dependencies> <dependency> <groupId>junit</groupId> <artifact

Spring整合CXF 客戶端及服務端

伺服器端: 1.新建Web專案,例如webws,匯入cxf-2.0.7/lib下的jar包和spring2.5的包,因為cxf支援spring,因此它自帶有sping的一些核心包,為了以後擴充套件,保險起見都一起匯入吧。。 2.新建一個服務介面IHelloWorld.java

spring整合cxf之SOAP方式

簡介 Apache CXF 是一個開源的 Services 框架,CXF 幫助您利用 Frontend 程式設計 API 來構建和開發 Services , 像 JAX-WS 。比如:HTTP

WebService學習之旅(三)JAX-WS與Spring整合釋出WebService

Spring本身就提供了對JAX-WS的支援,有興趣的讀者可以研究下Spring的Spring-WS專案,專案地址: http://docs.spring.io/spring-ws/sites/1.5/downloads/releases.html 基於Sp

activiti自定義流程之Spring整合activiti-modeler5.16例項(五):流程定義列表

1.流程定義依舊屬於流程資源,因此查詢流程定義也還是使用repositoryService進行操作 2.後臺業務程式碼,   (1)自定義的流程定義實體類:package model; pub

activiti自定義流程之Spring整合activiti-modeler5.16例項(一):環境搭建

專案中需要整合activiti-modeler自定義流程,找了很多資料後,終於成功的跳轉到activiti-modeler流程設計介面,以下是記錄: 一、整合基礎:eclipse4.4.1、tomcat7、jdk1.7、mysql5.6.25、maven3.2.5、acti

spring 整合cxf 第二彈(經過測試)以xml格式進行資料互動

為方便打大家學習以及應用,還是從配置檔案、jar、bean開始扯起。。。。。。 1,web.xml 配置檔案基本配置 <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi=

使用CXFSpring整合實現RESTFul WebService

以下引用與網路中!!!     一種軟體架構風格,設計風格而不是標準,只是提供了一組設計原則和約束條件。它主要用於客戶端和伺服器互動類的軟體。基於這個風格設計的軟體可以更簡潔,更有層次,更易於實現快取等機制。   &nbs

WebService Spring整合Jax-rs規範 使用CXF框架Restful的程式設計風格 編寫服務端

前提是專案SSM框架搭建好。 搭建cxf框架, 一、首先,將框架所需要的jar匯入,pom.xml檔案中 <!-- cxf 進行rs開發 必須匯入 --> <dependency> <groupId>org.apache.cx

一個CXF整合SPRINGWEBSERVICE完整例項

                1 首先準備以下JAR包activation.jarcommons-logging-1.1.1.jarcxf-2.5.6.jarjaxb-api-2.2.1.jarjaxb-impl-2.1.3.jarjaxws-api-2.2.8.jarneethi-3.0.2.jarow2

CXF WebService整合Spring

部分 控制 utf 內容 使用 mes classpath html row 首先,CXF和spring整合需要準備如下jar包文件: 這邊我是用Spring的jar包是Spring官方提供的,並沒有使用CXF中的Spring的jar文件。 添加這麽多文件後,首先在web