一个简单的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. <?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.        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
  5.     <bean id="payloadMapping" class="org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping">
  6.         <property name="endpointMap">
  7.             <map>
  8.                 <entry key="{http://www.ispring.com/ws/hello}eRequest"> 
  9.                     <ref bean="helloEndpoint"/>         
  10.                 </entry>
  11.             </map>      
  12.         </property> 
  13.     </bean>
  14.     
  15.     <bean id="hello" class="org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition"> 
  16.         <!--  --><property name="wsdl" value="classpath://hello.wsdl"></property>
  17.         <!-- <property name="wsdl" value="/WEB_INF/hello.wsdl"></property> -->
  18.         <!-- <constructor-arg value="/WEB_INF/hello.wsdl"/> -->
  19.     </bean>
  20.     
  21.     <bean id="helloEndpoint" class="com.sws.HelloEndPoint">
  22.         <property name="helloService" ref="helloService"></property>
  23.     </bean>
  24.     
  25.     <bean id="helloService" class="com.sws.HelloServiceImpl"></bean>
  26. </beans>

     其中最主要的bean就是payloadMapping, 它定义了接收到的messageendpoint之间的mapping关系:SOAP Body中包含的xml的根节点的QName{http://www.fuxueliang.com/ws/hello}HelloRequest交给helloEndpoint处理.
     SimpleWsdl11Definition这个bean则是定义了这个服务的wsdl, 访问地址是:

     http://localhost:8080/springws/hello.wsdl.

 

2、web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="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.   
  8.     <!-- begin Spring配置 
  9.     <context-param>
  10.         <param-name>contextConfigLocation</param-name>
  11.         <param-value>
  12.             /WEB-INF/spring-ws-servlet.xml,
  13.         </param-value>
  14.     </context-param>
  15.     <listener>
  16.         <listener-class>
  17.             org.springframework.web.context.ContextLoaderListener
  18.         </listener-class>
  19.     </listener>
  20.     <listener>
  21.         <listener-class>
  22.             org.springframework.web.util.IntrospectorCleanupListener
  23.         </listener-class>
  24.     </listener>-->
  25.     <!-- end Spring配置 -->
  26.     
  27.     <servlet>        
  28.         <servlet-name>spring-ws</servlet-name>         
  29.         <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>   
  30.     </servlet>   
  31.     <servlet-mapping>   
  32.         <servlet-name>spring-ws</servlet-name>   
  33.         <url-pattern>/*</url-pattern>   
  34.     </servlet-mapping> 
  35.   
  36.   <welcome-file-list>
  37.     <welcome-file>index.jsp</welcome-file>
  38.   </welcome-file-list>
  39.   
  40. </web-app>

3、hello.wsdl

  1. <?xml version="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.     
  9.     <wsdl:types>   
  10.         <schema xmlns="http://www.w3.org/2001/XMLSchema"
  11.                 targetNamespace="http://www.ispring.com/ws/hello">
  12.             <element name="dRequest" type="string" />
  13.             <element name="dResponse" type="string" />
  14.         </schema>   
  15.     </wsdl:types>   
  16.     
  17.     <wsdl:message name="bRequest">   
  18.         <wsdl:part element="schema:dRequest" name="cRequest" />   
  19.     </wsdl:message>   
  20.     <wsdl:message name="bResponse">   
  21.         <wsdl:part element="schema:dResponse" name="cResponse" />   
  22.     </wsdl:message>   
  23.     
  24.     <wsdl:portType name="HelloPortType">   
  25.         <wsdl:operation name="sayHello">   
  26.             <wsdl:input message="tns:bRequest" name="aRequest" />   
  27.             <wsdl:output message="tns:bResponse" name="aResponse" />   
  28.         </wsdl:operation>   
  29.     </wsdl:portType>   
  30.     
  31.     <wsdl:binding name="HelloBinding" type="tns:HelloPortType">   
  32.         <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http" />   
  33.         <wsdl:operation name="sayHello">   
  34.             <soap:operation soapAction="" />   
  35.             <wsdl:input name="aRequest">   
  36.                 <soap:body use="literal" />   
  37.             </wsdl:input>   
  38.             <wsdl:output name="aResponse">   
  39.                 <soap:body use="literal" />   
  40.             </wsdl:output>   
  41.         </wsdl:operation>   
  42.     </wsdl:binding>   
  43.     
  44.     <wsdl:service name="HelloService">   
  45.         <wsdl:port binding="tns:HelloBinding" name="HelloPort">   
  46.             <soap:address location="http://localhost:8088/springws/webservice" />   
  47.         </wsdl:port>   
  48.     </wsdl:service>   
  49. </wsdl:definitions>

4、HelloService.java

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

5、HelloServiceImpl.java

  1. package com.sws;
  2. public class 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. public class HelloEndPoint extends AbstractDomPayloadEndpoint{
  10.     /**
  11.      * Namespace of both request and response
  12.      */
  13.     public static final String NAMESPACE_URI = "http://www.ispring.com/ws/hello";
  14.     
  15.     /**
  16.      * The local name of the expected request
  17.      */
  18.     public static final String HELLO_REQUEST_LOCAL_NAME = "eRequest";
  19.     
  20.     /**
  21.      * The local name of the created response
  22.      */
  23.     public static final String HELLO_RESPONSE_LOCAL_NAME = "fResponse";
  24.     
  25.     private HelloService helloService;
  26.     
  27.     @Override
  28.     protected Element invokeInternal(Element requestElement, Document document)throws Exception {
  29.         Assert.isTrue(NAMESPACE_URI.equals(requestElement.getNamespaceURI()), "Invalid namespace");
  30.         Assert.isTrue(HELLO_REQUEST_LOCAL_NAME.equals(requestElement.getLocalName()), "Invalid local name");
  31.         
  32.         NodeList children = requestElement.getChildNodes();
  33.         Text requestText = null;
  34.         for(int i=0; i<children.getLength(); i++){
  35.             if(children.item(i).getNodeType() == Node.TEXT_NODE){
  36.                 requestText = (Text) children.item(i);
  37.             }
  38.         }
  39.         
  40.         if(requestText == null){
  41.             throw new IllegalArgumentException("Could not find request text node");
  42.         }
  43.         
  44.         String response = helloService.sayHello(requestText.getNodeValue());
  45.         Element responseElement = document.createElementNS(NAMESPACE_URI, HELLO_RESPONSE_LOCAL_NAME);
  46.         Text responseText = document.createTextNode(response);
  47.         responseElement.appendChild(responseText);
  48.         return responseElement;
  49.     }
  50.     public HelloService getHelloService() {
  51.         return helloService;
  52.     }
  53.     public void setHelloService(HelloService helloService) {
  54.         this.helloService = helloService;
  55.     }
  56. }

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. public class HelloWebServiceClient {
  15.     public static final String NAMESPACE_URI = "http://www.ispring.com/ws/hello";
  16.     
  17.     public static final String PREFIX = "tns";
  18.     
  19.     private SOAPConnectionFactory connectionFactory;
  20.     
  21.     private MessageFactory messageFactory;
  22.     
  23.     private URL url;
  24.     
  25.     public HelloWebServiceClient(String url) throws UnsupportedOperationException, SOAPException, MalformedURLException{
  26.         connectionFactory = SOAPConnectionFactory.newInstance();
  27.         messageFactory = MessageFactory.newInstance();
  28.         this.url = new URL(url);
  29.     }
  30.     
  31.     private SOAPMessage createHelloRequest() throws SOAPException{
  32.         SOAPMessage message = messageFactory.createMessage();
  33.         SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
  34.         Name helloRequestName = envelope.createName("eRequest",PREFIX,NAMESPACE_URI);
  35.         SOAPBodyElement helloRequestElement = message.getSOAPBody().addBodyElement(helloRequestName);
  36.         helloRequestElement.setValue("ispring");
  37.         return message;
  38.     }
  39.     
  40.     public void callWebService() throws SOAPException{
  41.         SOAPMessage request = createHelloRequest();
  42.         SOAPConnection connection = connectionFactory.createConnection();
  43.         SOAPMessage response = connection.call(request, url);
  44.         if(!response.getSOAPBody().hasFault()){
  45.             writeHelloResponse(response);
  46.         }else{
  47.             SOAPFault fault = response.getSOAPBody().getFault();
  48.             System.err.println("Received SOAP Fault");
  49.             System.err.println("SOAP Fault Code : " + fault.getFaultCode());
  50.             System.err.println("SOAP Fault String : " + fault.getFaultString());            
  51.         }
  52.     }
  53.     
  54.     private void writeHelloResponse(SOAPMessage message) throws SOAPException{
  55.         SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
  56.         Name helloResponseName = envelope.createName("fResponse",PREFIX,NAMESPACE_URI);
  57.         Iterator childElements = message.getSOAPBody().getChildElements(helloResponseName);
  58.         SOAPBodyElement helloResponseElement = (SOAPBodyElement)childElements.next();
  59.         String value = helloResponseElement.getTextContent();
  60.         System.out.println("Hello Response [" + value + "]");
  61.     }
  62.     
  63.     public static void main(String[] args) throws UnsupportedOperationException, MalformedURLException, SOAPException {
  64.         String url = "http://localhost:8088/SpringWS";
  65.         HelloWebServiceClient helloClient = new HelloWebServiceClient(url);
  66.         helloClient.callWebService();
  67.     }
  68. }

你可能感兴趣的:(spring,Web,schema,service,SOAP,encoding)