1. 程式人生 > >一個簡單的Spring Web Service示例

一個簡單的Spring Web Service示例

      剛接觸web service,好不容易找到一篇spring-ws的例子,還琢磨了好長一段時間,很多概念性的問題都沒弄清楚。只能依葫蘆畫瓢,照搬過來,稍微修改了一下,使結構更加清晰,原文出自http://fuxueliang.javaeye.com/blog/175184#。

     基本環境:

             JDK6、Tomcat 6.0、MyEclipse 6.6、spring 2.0、spring-ws-1.5.5

1、spring-ws-servlet.xml

      這個地方出現了一段插曲,hello.wsdl放在WEB-INF下老是報錯,說hello.wsdl找不到,後來放到classpath下才OK。

      建立一個Web專案, 由於Spring Web Service是基於Spring MVC, web.xml中新增如下servlet, 並在WEB-INF下建立SpringMVC的預設配置檔案spring-ws-servlet.xml:

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <beansxmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"
    >
  5. <beanid="payloadMapping"class="org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping">
  6. <propertyname="endpointMap">
  7. <map>
  8. <entrykey="{http://www.ispring.com/ws/hello}eRequest">
  9. <refbean="helloEndpoint"/>
  10. </entry>
  11. </map>
  12. </property>
  13. </bean>
  14. <beanid="hello"class="org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition">
  15. <!--  --><propertyname="wsdl"value="classpath://hello.wsdl"></property>
  16. <!-- <property name="wsdl" value="/WEB_INF/hello.wsdl"></property> -->
  17. <!-- <constructor-arg value="/WEB_INF/hello.wsdl"/> -->
  18. </bean>
  19. <beanid="helloEndpoint"class="com.sws.HelloEndPoint">
  20. <propertyname="helloService"ref="helloService"></property>
  21. </bean>
  22. <beanid="helloService"class="com.sws.HelloServiceImpl"></bean>
  23. </beans>

     其中最主要的bean就是payloadMapping, 它定義了接收到的messageendpoint之間的mapping關係:SOAP Body中包含的xml的根節點的QName{http://www.fuxueliang.com/ws/hello}HelloRequest交給helloEndpoint處理.
     SimpleWsdl11Definition這個bean則是定義了這個服務的wsdl, 訪問地址是:

2、web.xml

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <web-appversion="2.4"
  3. xmlns="http://java.sun.com/xml/ns/j2ee"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
  6.     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  7.     <!-- begin Spring配置 
  8. <context-param>
  9. <param-name>contextConfigLocation</param-name>
  10. <param-value>
  11.             /WEB-INF/spring-ws-servlet.xml,
  12. </param-value>
  13. </context-param>
  14. <listener>
  15. <listener-class>
  16.             org.springframework.web.context.ContextLoaderListener
  17. </listener-class>
  18. </listener>
  19. <listener>
  20. <listener-class>
  21.             org.springframework.web.util.IntrospectorCleanupListener
  22. </listener-class>
  23. </listener>-->
  24. <!-- end Spring配置 -->
  25. <servlet>
  26. <servlet-name>spring-ws</servlet-name>
  27. <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
  28. </servlet>
  29. <servlet-mapping>
  30. <servlet-name>spring-ws</servlet-name>
  31. <url-pattern>/*</url-pattern>
  32. </servlet-mapping>
  33. <welcome-file-list>
  34. <welcome-file>index.jsp</welcome-file>
  35. </welcome-file-list>
  36. </web-app>

3、hello.wsdl

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <wsdl:definitions
  3. xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
  4. xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
  5. xmlns:schema="http://www.ispring.com/ws/hello"
  6. xmlns:tns="http://www.ispring.com/ws/hello/definitions"
  7. targetNamespace="http://www.ispring.com/ws/hello/definitions">
  8. <wsdl:types>
  9. <schemaxmlns="http://www.w3.org/2001/XMLSchema"
  10. targetNamespace="http://www.ispring.com/ws/hello">
  11. <elementname="dRequest"type="string"/>
  12. <elementname="dResponse"type="string"/>
  13. </schema>
  14. </wsdl:types>
  15. <wsdl:messagename="bRequest">
  16. <wsdl:partelement="schema:dRequest"name="cRequest"/>
  17. </wsdl:message>
  18. <wsdl:messagename="bResponse">
  19. <wsdl:partelement="schema:dResponse"name="cResponse"/>
  20. </wsdl:message>
  21. <wsdl:portTypename="HelloPortType">
  22. <wsdl:operationname="sayHello">
  23. <wsdl:inputmessage="tns:bRequest"name="aRequest"/>
  24. <wsdl:outputmessage="tns:bResponse"name="aResponse"/>
  25. </wsdl:operation>
  26. </wsdl:portType>
  27. <wsdl:bindingname="HelloBinding"type="tns:HelloPortType">
  28. <soap:bindingstyle="document"transport="http://schemas.xmlsoap.org/soap/http"/>
  29. <wsdl:operationname="sayHello">
  30. <soap:operationsoapAction=""/>
  31. <wsdl:inputname="aRequest">
  32. <soap:bodyuse="literal"/>
  33. </wsdl:input>
  34. <wsdl:outputname="aResponse">
  35. <soap:bodyuse="literal"/>
  36. </wsdl:output>
  37. </wsdl:operation>
  38. </wsdl:binding>
  39. <wsdl:servicename="HelloService">
  40. <wsdl:portbinding="tns:HelloBinding"name="HelloPort">
  41. <soap:addresslocation="http://localhost:8088/springws/webservice"/>
  42. </wsdl:port>
  43. </wsdl:service>
  44. </wsdl:definitions>

4、HelloService.java

  1. package com.sws;
  2. publicinterface HelloService {
  3.     String sayHello(String name);
  4. }

5、HelloServiceImpl.java

  1. package com.sws;
  2. publicclass HelloServiceImpl implements HelloService {
  3. @Override
  4. public String sayHello(String name) {   
  5. return"Hello, " + name + "!";   
  6.     } 
  7. }

6、HelloEndPoint.java

     實現一個EndPoint來處理接收到的xml及返回xml.當然, Spring Web Service提供了很多抽象的實現, 包括Dom4j, JDom等等.這裡我們使用JDK自帶的, 需要繼承org.springframework.ws.server.endpoint.AbstractDomPayloadEndpoint.

  1. package com.sws;
  2. import org.springframework.util.Assert;
  3. import org.springframework.ws.server.endpoint.AbstractDomPayloadEndpoint;
  4. import org.w3c.dom.Document;
  5. import org.w3c.dom.Element;
  6. import org.w3c.dom.Node;
  7. import org.w3c.dom.NodeList;
  8. import org.w3c.dom.Text;
  9. publicclass HelloEndPoint extends AbstractDomPayloadEndpoint{
  10. /**
  11.      * Namespace of both request and response
  12.      */
  13. publicstaticfinal String NAMESPACE_URI = "http://www.ispring.com/ws/hello";
  14. /**
  15.      * The local name of the expected request
  16.      */
  17. publicstaticfinal String HELLO_REQUEST_LOCAL_NAME = "eRequest";
  18. /**
  19.      * The local name of the created response
  20.      */
  21. publicstaticfinal String HELLO_RESPONSE_LOCAL_NAME = "fResponse";
  22. private HelloService helloService;
  23. @Override
  24. protected Element invokeInternal(Element requestElement, Document document)throws Exception {
  25.         Assert.isTrue(NAMESPACE_URI.equals(requestElement.getNamespaceURI()), "Invalid namespace");
  26.         Assert.isTrue(HELLO_REQUEST_LOCAL_NAME.equals(requestElement.getLocalName()), "Invalid local name");
  27.         NodeList children = requestElement.getChildNodes();
  28.         Text requestText = null;
  29. for(int i=0; i<children.getLength(); i++){
  30. if(children.item(i).getNodeType() == Node.TEXT_NODE){
  31.                 requestText = (Text) children.item(i);
  32.             }
  33.         }
  34. if(requestText == null){
  35. thrownew IllegalArgumentException("Could not find request text node");
  36.         }
  37.         String response = helloService.sayHello(requestText.getNodeValue());
  38.         Element responseElement = document.createElementNS(NAMESPACE_URI, HELLO_RESPONSE_LOCAL_NAME);
  39.         Text responseText = document.createTextNode(response);
  40.         responseElement.appendChild(responseText);
  41. return responseElement;
  42.     }
  43. public HelloService getHelloService() {
  44. return helloService;
  45.     }
  46. publicvoid setHelloService(HelloService helloService) {
  47. this.helloService = helloService;
  48.     }
  49. }

7、HelloWebServiceClient.java(saaj實現)

  1. package com.sws;
  2. import java.net.MalformedURLException;
  3. import java.net.URL;
  4. import java.util.Iterator;
  5. import javax.xml.soap.MessageFactory;
  6. import javax.xml.soap.Name;
  7. import javax.xml.soap.SOAPBodyElement;
  8. import javax.xml.soap.SOAPConnection;
  9. import javax.xml.soap.SOAPConnectionFactory;
  10. import javax.xml.soap.SOAPEnvelope;
  11. import javax.xml.soap.SOAPException;
  12. import javax.xml.soap.SOAPFault;
  13. import javax.xml.soap.SOAPMessage;
  14. publicclass HelloWebServiceClient {
  15. publicstaticfinal String NAMESPACE_URI = "http://www.ispring.com/ws/hello";
  16. publicstaticfinal String PREFIX = "tns";
  17. private SOAPConnectionFactory connectionFactory;
  18. private MessageFactory messageFactory;
  19. private URL url;
  20. public HelloWebServiceClient(String url) throws UnsupportedOperationException, SOAPException, MalformedURLException{
  21.         connectionFactory = SOAPConnectionFactory.newInstance();
  22.         messageFactory = MessageFactory.newInstance();
  23. this.url = new URL(url);
  24.     }
  25. private SOAPMessage createHelloRequest() throws SOAPException{
  26.         SOAPMessage message = messageFactory.createMessage();
  27.         SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
  28.         Name helloRequestName = envelope.createName("eRequest",PREFIX,NAMESPACE_URI);
  29.         SOAPBodyElement helloRequestElement = message.getSOAPBody().addBodyElement(helloRequestName);
  30.         helloRequestElement.setValue("ispring");
  31. return message;
  32.     }
  33. publicvoid callWebService() throws SOAPException{
  34.         SOAPMessage request = createHelloRequest();
  35.         SOAPConnection connection = connectionFactory.createConnection();
  36.         SOAPMessage response = connection.call(request, url);
  37. if(!response.getSOAPBody().hasFault()){
  38.             writeHelloResponse(response);
  39.         }else{
  40.             SOAPFault fault = response.getSOAPBody().getFault();
  41.             System.err.println("Received SOAP Fault");
  42.             System.err.println("SOAP Fault Code : " + fault.getFaultCode());
  43.             System.err.println("SOAP Fault String : " + fault.getFaultString());            
  44.         }
  45.     }
  46. privatevoid writeHelloResponse(SOAPMessage message) throws SOAPException{
  47.         SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
  48.         Name helloResponseName = envelope.createName("fResponse",PREFIX,NAMESPACE_URI);
  49.         Iterator childElements = message.getSOAPBody().getChildElements(helloResponseName);
  50.         SOAPBodyElement helloResponseElement = (SOAPBodyElement)childElements.next();
  51.         String value = helloResponseElement.getTextContent();
  52.         System.out.println("Hello Response [" + value + "]");
  53.     }
  54. publicstaticvoid main(String[] args) throws UnsupportedOperationException, MalformedURLException, SOAPException {
  55.         String url = "http://localhost:8088/SpringWS";
  56.         HelloWebServiceClient helloClient = new HelloWebServiceClient(url);
  57.         helloClient.callWebService();
  58.     }
  59. }