Java創建WebService服務及客戶端實現

 分類:

目錄(?)[+]

簡介       

       WebService是一種服務的提供方式,通過WebService,不同應用間相互間調用變的很方便,網絡上有很多常用的WebService服務,如:http://developer.51cto.com/art/200908/147125.htm,不同的語言平臺對WebService都有實現,Java的WebService實現,比較流行的有Axis2、Jaxws,本文介紹的是Axis2。

Axis2下載和部署

       Axis2是Apache開發的一個開源項目,再次感嘆Apache的偉大!

       下載地址:

       http://mirror.bit.edu.cn/apache/axis/axis2/java/core/1.6.2/axis2-1.6.2-war.zip

       將其內axis2.war解壓到<Tomcat安裝目錄>/webapps下,啓動Tomcat,war包會自動解壓,

       訪問http://localhost:8080/axis2/,如果看到歡迎主頁,則說明部署成功。

配置Axis2

       <Tomcat安裝目錄>/webapps/axis2/WEB-INF/conf/axis2.xml,配置其內兩個屬性,以便調試。

[html] view plain copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. <parameter name="hotdeployment">true</parameter><!-- 開啓熱部署,不需要重啓即可部署服務 -->  
  2. <parameter name="hotupdate">true</parameter><!-- 開啓熱更新,不需要重啓即可更新服務 -->  

編寫服務

       所謂服務就是編寫一個類,寫一些方法,方法返回數據,WebService客戶端獲取數據。

[java] view plain copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. public class HelloService {  
  2.   
  3.     public String sayHello() {  
  4.         return "hello";  
  5.     }  
  6.       
  7. }  

零配置發佈服務

       服務類創建好後,我們需要發佈到服務器上,將HelloService.class放到<Tomcat安裝目錄>/webapps/axis2/WEB-INF/pojo下,pojo沒有需要創建。

       至此,我們已經成功的創建了一個WebService服務了,so easy!

       再次訪問http://localhost:8080/axis2/,點擊Services,可以發現可用services中多了一個HelloService,其內有一個可用操作sayHello,說明發布成功。

[java] view plain copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. HelloService  
  2.   
  3. Service Description : No description available for this service  
  4.   
  5. Service EPR : http://localhost:8080/axis2/services/HelloService  
  6.   
  7. Service Status : Active  
  8.   
  9.   
  10. Available Operations  
  11. sayHello  
       訪問http://localhost:8080/axis2/services/HelloService,頁面輸出正是我們的返回值。

[html] view plain copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. <ns:sayHelloResponse xmlns:ns="http://ws.apache.org/axis2">  
  2. <return>hello</return>  
  3. </ns:sayHelloResponse>  
       這裏有兩點需要注意:

       - 發佈的類不能放在包裏,既不能使用package關鍵字;

       - 默認的發佈目錄是pojo,可以在<Tomcat安裝目錄>/webapps/axis2/WEB-INF/conf/axis2.xml中增加目錄,

[html] view plain copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. <deployer extension=".class" directory="<要增加的目錄名稱>" class="org.apache.axis2.deployment.POJODeployer" />  
         要注意多個目錄間WebService要唯一,否則會重名,重名後,先部署的會成功,後部署的會報錯。

services.xml配置文件發佈服務

       雖然上面的方式不需要配置文件,但是其服務類不能放在包內,顯然是不符合我們日常開發的,Axis2也允許帶包的類發佈WebService,如果不允許,估計就沒人用了。

       首先寫一個較複雜的服務類,多個方法,帶參數,有返回值的。

[java] view plain copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. package webservice.test;  
  2.   
  3. /** 
  4.  * 計算器運算 
  5.  *  
  6.  * @author gaoshuang 
  7.  */  
  8. public class CalculateService {  
  9.   
  10.     // 加法  
  11.     public float plus(float x, float y) {  
  12.         return x + y;  
  13.     }  
  14.   
  15.     // 減法  
  16.     public float minus(float x, float y) {  
  17.         return x - y;  
  18.     }  
  19.   
  20.     // 乘法  
  21.     public float multiply(float x, float y) {  
  22.         return x * y;  
  23.     }  
  24.   
  25.     // 除法  
  26.     public float divide(float x, float y) {  
  27.         if (y != 0)  
  28.             return x / y;  
  29.         else  
  30.             return -1;  
  31.     }  
  32. }  
       然後編寫services.xml,該文件需要放在META-INF文件夾下。

[html] view plain copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!-- 服務名稱 -->  
  3. <service name="CalculateService">  
  4.     <!-- 服務描述 -->  
  5.     <description>  
  6.         加減乘除計算服務  
  7.     </description>  
  8.     <!-- 設置服務類 -->  
  9.     <parameter name="ServiceClass">  
  10.         com.runqianapp.webservice.test.CalculateService  
  11.     </parameter>  
  12.     <!-- 方法 -->  
  13.     <operation name="plus">  
  14.         <!-- 方法處理器,RPCMessageReceiver爲帶返回值的處理器,  
  15.                      RPCInOnlyMessageReceiver爲不帶返回值的處理器 -->  
  16.         <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"  
  17.             class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />  
  18.     </operation>  
  19.     <operation name="minus">  
  20.         <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"  
  21.             class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />  
  22.     </operation>  
  23.     <operation name="multiply">  
  24.         <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"  
  25.             class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />  
  26.     </operation>  
  27.     <operation name="divide">  
  28.         <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out"  
  29.             class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />  
  30.     </operation>  
  31. </service>  

       最後將這兩個文件打成jar包,不論用工具還是手動打,打的都是最外層的文件夾。

       

       我打的名字是server.jar,更改後綴爲aar,所以最後是server.aar,Axis2建議使用aar發佈WebService,

       將server.aar放到<Tomcat安裝目錄>/webapps/axis2/WEB-INF/services下,訪問http://localhost:8080/axis2/services/listServices

       多出了一個CalculateService,說明發布成功。

[java] view plain copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. CalculateService  
  2.   
  3. Service Description : CalculateService  
  4.   
  5. Service EPR : http://localhost:8080/axis2/services/CalculateService  
  6.   
  7. Service Status : Active  
  8.   
  9.   
  10. Available Operations  
  11. divide  
  12. plus  
  13. minus  
  14. multiply  
       分別訪問

       http://localhost:8080/axis2/services/CalculateService/plus?x=1&y=2

       http://localhost:8080/axis2/services/CalculateService/divide?x=1&y=2

       http://localhost:8080/axis2/services/CalculateService/minus?x=1&y=2

       http://localhost:8080/axis2/services/CalculateService/multiply?x=1&y=2
       也可以發佈多個WebService,可以使用serviceGroup標籤。

[html] view plain copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. <serviceGroup>  
  2. <service name="myService1">  
  3.     ...  
  4. </service>  
  5. <service name="myService2">  
  6.     ...  
  7. </service>  
  8. </serviceGroup>  

客戶端實現

       以上介紹的都是WebService服務創建及發佈,那麼有了一個WebService服務後,我們如何調用呢?只在瀏覽器上訪問是沒有意義的。

       下載Axis2客戶端壓縮包:http://mirror.esocc.com/apache/axis/axis2/java/core/1.6.2/axis2-1.6.2-bin.zip,並解壓。

       新建工程WebServiceClientTest,將<Axis2客戶端安裝目錄>/lib下所有jar包添加到工程中;

       編寫客戶端代碼;

[java] view plain copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. package webservice.client.test;  
  2.   
  3. import javax.xml.namespace.QName;  
  4.   
  5. import org.apache.axis2.AxisFault;  
  6. import org.apache.axis2.addressing.EndpointReference;  
  7. import org.apache.axis2.client.Options;  
  8. import org.apache.axis2.rpc.client.RPCServiceClient;  
  9.   
  10. public class Client1 {  
  11.   
  12.     /** 
  13.      * @param args 
  14.      * @throws AxisFault 
  15.      */  
  16.     public static void main(String[] args) throws AxisFault {  
  17.         // 使用RPC方式調用WebService  
  18.         RPCServiceClient serviceClient = new RPCServiceClient();  
  19.         Options options = serviceClient.getOptions();  
  20.         // 指定調用WebService的URL  
  21.         EndpointReference targetEPR = new EndpointReference(  
  22.                 "http://localhost:8080/axis2/services/CalculateService");  
  23.         options.setTo(targetEPR);  
  24.         // 調用方法的參數值  
  25.         Object[] entryArgs = new Object[] {12};  
  26.         // 調用方法返回值的數據類型的Class對象  
  27.         Class[] classes = new Class[] { float.class };  
  28.         // 調用方法名及WSDL文件的命名空間  
  29.         // 命名空間是http://localhost:8080/axis2/services/CalculateService?wsdl中wsdl:definitions標籤targetNamespace屬性  
  30.         QName opName = new QName("http://test.webservice""plus");  
  31.         // 執行方法獲取返回值  
  32.         // 沒有返回值的方法使用serviceClient.invokeRobust(opName, entryArgs)  
  33.         Object result = serviceClient.invokeBlocking(opName, entryArgs, classes)[0];  
  34.         System.out.println(result);  
  35.         // out: 3.0  
  36.     }  
  37.   
  38. }  
       以上是實現了一個簡單的WebSerivce客戶端,調用CalculateService中的plus方法,由代碼可見,這種調用方式比較雜亂,代碼不太友好。

wsdl2java簡化客戶端

       <Axis2客戶端安裝目錄>/bin目錄,其內有兩個bat,wsdl2java.bat和java2wsdl.bat,可以實現WSDL文件和Java之間的互相轉換。

       考慮到我們以後可能經常使用這些命令,設置環境變量,方便以後調用。在系統變量中加入AXIS2_HOME=<Axis2客戶端安裝目錄>,path中追加;%AXIS2_HOME%\bin。

       啓動命令提示符,進入WebServiceTestClient所在目錄,運行

[plain] view plain copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. wsdl2java -uri http://localhost:8080/axis2/services/CalculateService?wsdl -p webservice.client.test -s  
       參數說明:uri - wsdl文件路徑,網絡路徑或本地路徑,p - 打包,這裏和上一個客戶端實現類打在了一個包裏,wsdl2java有很多參數,詳細可以運行該命令去查看。

       執行後,如果沒有報錯,說明運行成功,刷新項目,該包下多出了一個CalculateServiceStub類,裏面的代碼極其複雜,還亂呼呼的,這我們不用管,調用該類。

[java] view plain copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. package webservice.client.test;  
  2.   
  3. import java.rmi.RemoteException;  
  4.   
  5. import webservice.client.test.CalculateServiceStub.Plus;  
  6.   
  7. public class Client2 {  
  8.   
  9.     /** 
  10.      * @param args 
  11.      * @throws RemoteException  
  12.      */  
  13.     public static void main(String[] args) throws RemoteException {  
  14.         CalculateServiceStub stub = new CalculateServiceStub();  
  15.         Plus plus = new Plus();  
  16.         plus.setX(1);  
  17.         plus.setY(2);  
  18.         float result = stub.plus(plus).get_return();// 返回值自動轉型,這也是強大之處  
  19.         System.out.println(result);  
  20.     }  
  21.   
  22. }  

       如此做的好處就是調用時不需要在去查看WSDL,和正常使用一個類一樣,對WebService的封裝都由wsdl2java自動生成,代碼更優雅、簡潔。

利用wsdl2java輕鬆使用第三方WebService服務

       有了wsdl2java,已知一個WSDL文件我們就可以輕鬆的生成WebService客戶端供我們調用,給我們服務。文章開頭給出的鏈接包含了一些第三方服務,有一個服務是生成隨機個數中文,WSDL:http://www.webxml.com.cn/WebServices/RandomFontsWebService.asmx?wsdl,同樣,啓動命令提示符,進入項目路徑,執行

[plain] view plain copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. wsdl2java -uri http://www.webxml.com.cn/WebServices/RandomFontsWebService.asmx?wsdl -p webservice.client.test -s  
       調用該類

[java] view plain copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. package webservice.client.test;  
  2.   
  3. import java.rmi.RemoteException;  
  4.   
  5. import webservice.client.test.RandomFontsWebServiceStub.ArrayOfString;  
  6. import webservice.client.test.RandomFontsWebServiceStub.GetChineseFonts;  
  7.   
  8. public class ThirdClient {  
  9.   
  10.     /** 
  11.      * @param args 
  12.      * @throws RemoteException  
  13.      */  
  14.     public static void main(String[] args) throws RemoteException {  
  15.         RandomFontsWebServiceStub stub = new RandomFontsWebServiceStub();  
  16.         GetChineseFonts getChineseFonts = new GetChineseFonts();  
  17.         getChineseFonts.setByFontsLength(10);// 免費使用有限制,最多8個  
  18.         ArrayOfString result = stub.getChineseFonts(getChineseFonts).getGetChineseFontsResult();  
  19.         for(String str : result.getString()) {  
  20.             System.out.println(str);  
  21.         }  
  22.     }  
  23.   
  24. }  

源碼下載

       文中代碼盡在下面鏈接中,免積分下載。

       http://download.csdn.net/download/ghsau/6400843

       (完)

       本文來自:高爽|Coder,原文地址:http://blog.csdn.net/ghsau/article/details/12714965

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章