利用Java編寫簡單的WebService實例

轉自http://nopainnogain.iteye.com/blog/791525 

 使用Axis編寫WebService比較簡單,就我的理解,WebService的實現代碼和編寫Java代碼其實沒有什麼區別,主要是將哪些Java類發佈爲WebService。下面是一個從編寫測試例子到發佈WebService,以及編寫測試代碼的過程介紹。

      本例子的WebService提供了兩個方法,分別是sayHello和sayHelloToPerson,第一個只是返回一個"Hello"字符串,沒有參數,第二個函數接受一個字符串作爲參數,返回"Hello 參數值",該例子比較簡單,但是清楚的說明了從編寫代碼到發佈爲WebService以及測試編寫好的WebService全過程。

編寫服務代碼

      服務代碼提供了兩個函數,分別爲sayHello和sayHelloToPerson,源代碼如下:

Java代碼  收藏代碼
  1. /* 
  2.  * File name: HelloService.java 
  3.  *  
  4.  * Version: v1.0 
  5.  *  
  6.  * Created on Aug 2, 2008 9:40:20 AM 
  7.  *  
  8.  * Designed by Stephen 
  9.  *  
  10.  * (c)Copyright 2008 
  11.  */  
  12. package com.sinosoft.webservice;  
  13.   
  14. /** *//** 
  15.  * @author Stephen 
  16.  *  
  17.  * Test web service 
  18.  */  
  19. public class HelloService {  
  20.     /** *//** 
  21.      * 不帶參數的函數 
  22.      *  
  23.      * @return 返回Hello字符串 
  24.      */  
  25.     public String sayHello() {  
  26.         return "Hello";  
  27.     }  
  28.   
  29.     /** *//** 
  30.      * 帶參數的函數 
  31.      *  
  32.      * @param name 
  33.      *            名稱 
  34.      * @return 返回加上名稱的歡迎詞 
  35.      */  
  36.     public String sayHelloToPerson(String name) {  
  37.         if (name == null || name.equals("")) {  
  38.             name = "nobody";  
  39.         }  
  40.         return "Hello " + name;  
  41.     }  
  42. }  

 

 

發佈WebService

      要將上邊寫的HelloService類發佈爲WebService,需要先搭建Web應用。下面是在Tomcat下使用Axis(http://ws.apache.org/axis/)創建WebService服務的例子。

在Tomcat下創建Web應用

在該例子中,在Tomcat下創建了一個context path爲ws的WEB應用。

     1. 在myeclipse中創建WebServiceTest的webproject

     2. 在WEB-INF文件夾下web.xml文件,該文件的內容如下:

Xml代碼  收藏代碼
  1. <?xml version="1.0" encoding="ISO-8859-1"?>  
  2.   
  3. <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web  
  4. Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">  
  5.   
  6. <web-app>  
  7.   <display-name>Apache-Axis</display-name>  
  8.       
  9.     <listener>  
  10.         <listener-class>org.apache.axis.transport.http.AxisHTTPSessionListener</listener-class>  
  11.     </listener>  
  12.       
  13.   <servlet>  
  14.     <servlet-name>AxisServlet</servlet-name>  
  15.     <display-name>Apache-Axis Servlet</display-name>  
  16.     <servlet-class>  
  17.         org.apache.axis.transport.http.AxisServlet  
  18.     </servlet-class>  
  19.   </servlet>  
  20.   
  21.   <servlet>  
  22.     <servlet-name>AdminServlet</servlet-name>  
  23.     <display-name>Axis Admin Servlet</display-name>  
  24.     <servlet-class>  
  25.         org.apache.axis.transport.http.AdminServlet  
  26.     </servlet-class>  
  27.     <load-on-startup>100</load-on-startup>  
  28.   </servlet>  
  29.   
  30.   <servlet>  
  31.     <servlet-name>SOAPMonitorService</servlet-name>  
  32.     <display-name>SOAPMonitorService</display-name>  
  33.     <servlet-class>  
  34.         org.apache.axis.monitor.SOAPMonitorService  
  35.     </servlet-class>  
  36.     <init-param>  
  37.       <param-name>SOAPMonitorPort</param-name>  
  38.       <param-value>5001</param-value>  
  39.     </init-param>  
  40.     <load-on-startup>100</load-on-startup>  
  41.   </servlet>  
  42.   
  43.   <servlet-mapping>  
  44.     <servlet-name>AxisServlet</servlet-name>  
  45.     <url-pattern>/servlet/AxisServlet</url-pattern>  
  46.   </servlet-mapping>  
  47.   
  48.   <servlet-mapping>  
  49.     <servlet-name>AxisServlet</servlet-name>  
  50.     <url-pattern>*.jws</url-pattern>  
  51.   </servlet-mapping>  
  52.   
  53.   <servlet-mapping>  
  54.     <servlet-name>AxisServlet</servlet-name>  
  55.     <url-pattern>/services/*</url-pattern>  
  56.   </servlet-mapping>  
  57.   
  58.   <servlet-mapping>  
  59.     <servlet-name>SOAPMonitorService</servlet-name>  
  60.     <url-pattern>/SOAPMonitor</url-pattern>  
  61.   </servlet-mapping>  
  62.   
  63.  <!-- uncomment this if you want the admin servlet -->  
  64.  <!--  
  65.   <servlet-mapping>  
  66.     <servlet-name>AdminServlet</servlet-name>  
  67.     <url-pattern>/servlet/AdminServlet</url-pattern>  
  68.   </servlet-mapping>  
  69.  -->  
  70.   
  71.     <session-config>  
  72.         <!-- Default to 5 minute session timeouts -->  
  73.         <session-timeout>5</session-timeout>  
  74.     </session-config>  
  75.   
  76.     <!-- currently the W3C havent settled on a media type for WSDL;  
  77.     http://www.w3.org/TR/2003/WD-wsdl12-20030303/#ietf-draft  
  78.     for now we go with the basic 'it's XML' response -->  
  79.   <mime-mapping>  
  80.     <extension>wsdl</extension>  
  81.      <mime-type>text/xml</mime-type>  
  82.   </mime-mapping>  
  83.     
  84.   
  85.   <mime-mapping>  
  86.     <extension>xsd</extension>  
  87.     <mime-type>text/xml</mime-type>  
  88.   </mime-mapping>  
  89.   
  90.   <welcome-file-list id="WelcomeFileList">  
  91.     <welcome-file>index.jsp</welcome-file>  
  92.     <welcome-file>index.html</welcome-file>  
  93.     <welcome-file>index.jws</welcome-file>  
  94.   </welcome-file-list>  
  95.   
  96. </web-app>  

 

 

在上面的web.xml中主要是配置了axis的相關配置。

axis的相關配置

在上述的web.xml文件中已經對axis進行了配置,但是還需要進行額外的配置。

     複製axis相關的jar文件

     將axis的相關jar文件複製到WEB-INF\lib文件夾下。這些文件包括:

activation.jar
axis.jar
axis-ant.jar
commons-discovery-0.2.jar
commons-logging-1.0.4.jar
jaxrpc.jar
log4j-1.2.8.jar
saaj.jar
wsdl4j-1.5.1.jar

  

測試發佈的Web應用

啓動Tomcat服務,打開IE瀏覽器,訪問地址http://127.0.0.1:8080/WebServiceTest/services,如果看到如下界面就說明AXIS部署成功了。

 

 

發佈WebService

     發佈WebService需要使用現有的AdminService來實現,這裏我寫了一個批處理文件來發布WebService,以後如果需要發佈其他文件,只需要修改相應的參數就可以了。

創建deploy.wsdd文件

文件deploy.wsdd內容如下所示:

Xml代碼  收藏代碼
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <deployment xmlns="http://xml.apache.org/axis/wsdd/" xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">  
  3.     <service name="HelloServices" provider="java:RPC">  
  4.         <parameter name="className" value="com.sinosoft.webservice.HelloService"/>  
  5.         <parameter name="allowedMethods" value="*"/>  
  6.     </service>  
  7. </deployment>  

 

 

創建發佈WebService服務的批處理文件

批處理文件deploywebservice.bat內容如下:

Xml代碼  收藏代碼
  1. java -cp axis-ant.jar;axis-schema.jar;axis.jar;commons-discovery-0.2.jar;commons-logging-1.0.4.jar;jaxrpc.jar;log4j-1.2.8.jar;saaj.jar;wsdl4j-1.5.1.jar;xmlsec-1.3.0.jar org.apache.axis.client.AdminClient -lhttp://localhost:8080/WebServiceTest/services/AdminService deploy.wsdd  
  2.   
  3. pause  

 

 

  其中上面的jar包我都拷到和bat文件在同一個目錄,現在將所有的jar文件都加入到classpath中進行執行。

     -l後的參數是本地要發佈WebService的AdminService對應的訪問地址。

     最後deploy.wsdd是對應的配置文件名稱。

發佈WebService服務

將deploy.wsdd文件和deploywebservice.bat文件複製到同一個文件夾下,執行deploywebservice.bat批處理文件,就可以將deploy.wsdd中描述的Java類發佈爲WebService。發佈完成之後在訪問http://host:port/ws/services如下圖所示:

 

 

從上圖可以看出,發佈成功後,多了一個HelloServices的服務。這樣就說明HelloService發佈成功了。

查看HelloServices的wsdl

     訪問http://127.0.0.1:8080/WebServiceTest/services/HelloServices?wsdl可以看到如下wsdl的內容:

Xml代碼  收藏代碼
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <wsdl:definitions targetNamespace="http://127.0.0.1:8080/WebServiceTest/services/HelloServices" xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:impl="http://127.0.0.1:8080/WebServiceTest/services/HelloServices" xmlns:intf="http://127.0.0.1:8080/WebServiceTest/services/HelloServices" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">  
  3. <!--WSDL created by Apache Axis version: 1.4  
  4. Built on Apr 22, 2006 (06:55:48 PDT)-->  
  5.   
  6.    <wsdl:message name="sayHelloToPersonRequest">  
  7.   
  8.       <wsdl:part name="name" type="soapenc:string"/>  
  9.   
  10.    </wsdl:message>  
  11.   
  12.    <wsdl:message name="sayHelloRequest">  
  13.   
  14.    </wsdl:message>  
  15.   
  16.    <wsdl:message name="sayHelloToPersonResponse">  
  17.   
  18.       <wsdl:part name="sayHelloToPersonReturn" type="soapenc:string"/>  
  19.   
  20.    </wsdl:message>  
  21.   
  22.    <wsdl:message name="sayHelloResponse">  
  23.   
  24.       <wsdl:part name="sayHelloReturn" type="soapenc:string"/>  
  25.   
  26.    </wsdl:message>  
  27.   
  28.    <wsdl:portType name="HelloService">  
  29.   
  30.       <wsdl:operation name="sayHello">  
  31.   
  32.          <wsdl:input message="impl:sayHelloRequest" name="sayHelloRequest"/>  
  33.   
  34.          <wsdl:output message="impl:sayHelloResponse" name="sayHelloResponse"/>  
  35.   
  36.       </wsdl:operation>  
  37.   
  38.       <wsdl:operation name="sayHelloToPerson" parameterOrder="name">  
  39.   
  40.          <wsdl:input message="impl:sayHelloToPersonRequest" name="sayHelloToPersonRequest"/>  
  41.   
  42.          <wsdl:output message="impl:sayHelloToPersonResponse" name="sayHelloToPersonResponse"/>  
  43.   
  44.       </wsdl:operation>  
  45.   
  46.    </wsdl:portType>  
  47.   
  48.    <wsdl:binding name="HelloServicesSoapBinding" type="impl:HelloService">  
  49.   
  50.       <wsdlsoap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>  
  51.   
  52.       <wsdl:operation name="sayHello">  
  53.   
  54.          <wsdlsoap:operation soapAction=""/>  
  55.   
  56.          <wsdl:input name="sayHelloRequest">  
  57.   
  58.             <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://webservice.sinosoft.com" use="encoded"/>  
  59.   
  60.          </wsdl:input>  
  61.   
  62.          <wsdl:output name="sayHelloResponse">  
  63.   
  64.             <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://127.0.0.1:8080/WebServiceTest/services/HelloServices" use="encoded"/>  
  65.   
  66.          </wsdl:output>  
  67.   
  68.       </wsdl:operation>  
  69.   
  70.       <wsdl:operation name="sayHelloToPerson">  
  71.   
  72.          <wsdlsoap:operation soapAction=""/>  
  73.   
  74.          <wsdl:input name="sayHelloToPersonRequest">  
  75.   
  76.             <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://webservice.sinosoft.com" use="encoded"/>  
  77.   
  78.          </wsdl:input>  
  79.   
  80.          <wsdl:output name="sayHelloToPersonResponse">  
  81.   
  82.             <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://127.0.0.1:8080/WebServiceTest/services/HelloServices" use="encoded"/>  
  83.   
  84.          </wsdl:output>  
  85.   
  86.       </wsdl:operation>  
  87.   
  88.    </wsdl:binding>  
  89.   
  90.    <wsdl:service name="HelloServiceService">  
  91.   
  92.       <wsdl:port binding="impl:HelloServicesSoapBinding" name="HelloServices">  
  93.   
  94.          <wsdlsoap:address location="http://127.0.0.1:8080/WebServiceTest/services/HelloServices"/>  
  95.   
  96.       </wsdl:port>  
  97.   
  98.    </wsdl:service>  
  99.   
  100. </wsdl:definitions>  

 

用Java調用WebService實例

     下面是用Java調用剛發佈的WebService例子。

 

Java代碼  收藏代碼
  1. /* 
  2.  * File name: TestHelloService.java 
  3.  *  
  4.  * Version: v1.0 
  5.  *  
  6.  * Created on Aug 2, 2008 9:54:10 AM 
  7.  *  
  8.  * Designed by Stephen 
  9.  *  
  10.  * (c)Copyright 2008 
  11.  */  
  12. package test.com.sinosoft.webservice;  
  13.   
  14. import java.io.IOException;  
  15. import java.net.MalformedURLException;  
  16.   
  17. import javax.xml.namespace.QName;  
  18. import javax.xml.rpc.ServiceException;  
  19.   
  20. import org.apache.axis.client.Call;  
  21. import org.apache.axis.client.Service;  
  22. import org.apache.commons.logging.Log;  
  23. import org.apache.commons.logging.LogFactory;  
  24.   
  25. /** 
  26.  * @author Stephen 
  27.  *  
  28.  * 測試調用WebService 
  29.  */  
  30. public class TestHelloService {  
  31.     private static final Log log = LogFactory.getLog(TestHelloService.class);  
  32.     private static final String HELLO_SERVICE_ENDPOINT = "http://127.0.0.1:8080/WebServiceTest/services/HelloServices?wsdl";  
  33.   
  34.     public static void main(String[] args) {  
  35.         TestHelloService tester = new TestHelloService();  
  36.         // tester.callSayHello();  
  37.         tester.callSayHelloToPerson();  
  38.     }  
  39.   
  40.     public void callSayHello() {  
  41.         try {  
  42.             Service service = new Service();  
  43.             Call call = (Call) service.createCall();  
  44.             call.setTargetEndpointAddress(new java.net.URL(  
  45.                     HELLO_SERVICE_ENDPOINT));  
  46.             //下面名字查詢的http://127.0.0.1:8080/WebServiceTest/services/HelloServices?wsdl文件裏有  
  47.             call.setOperationName(new QName("http://webservice.sinosoft.com/",  
  48.                     "sayHello"));  
  49.             call.setReturnType(org.apache.axis.Constants.XSD_STRING);  
  50.             try {  
  51.                 //遠程調用發佈的方法  
  52.                 String ret = (String) call.invoke(new Object[] {});  
  53.                 System.out.println("The return value is:" + ret);  
  54.                 return;  
  55.             } catch (IOException e) {  
  56.                 e.printStackTrace();  
  57.             }  
  58.         } catch (MalformedURLException e) {  
  59.             e.printStackTrace();  
  60.         } catch (ServiceException e) {  
  61.             e.printStackTrace();  
  62.         }  
  63.         log.error("call sayHello service error!");  
  64.     }  
  65.   
  66.     public void callSayHelloToPerson() {  
  67.         try {  
  68.             Service service = new Service();  
  69.             Call call = (Call) service.createCall();  
  70.             call.setTargetEndpointAddress(new java.net.URL(HELLO_SERVICE_ENDPOINT));  
  71.             call.setOperationName(new QName("http://webservice.sinosoft.com/",  
  72.                     "sayHelloToPerson"));  
  73.             call.addParameter("name", org.apache.axis.Constants.XSD_STRING,  
  74.                     javax.xml.rpc.ParameterMode.IN);  
  75.             call.setReturnType(org.apache.axis.Constants.XSD_STRING);  
  76.             try {  
  77.                 String ret = (String) call.invoke(new Object[] { "Stephen" });  
  78.                 System.out.println("The return value is:" + ret);  
  79.                 return;  
  80.             } catch (IOException e) {  
  81.                 e.printStackTrace();  
  82.             }  
  83.         } catch (MalformedURLException e) {  
  84.             e.printStackTrace();  
  85.         } catch (ServiceException e) {  
  86.             e.printStackTrace();  
  87.         }  
  88.         log.error("call sayHello service error!");  
  89.     }  
  90. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章