Spring Web Service 学习之Hello World篇

Spring Web Service是Spring社区基于Spring提供的一个关注于创建”文档驱动”的Web Service的模块, 它的主要目标是方便基于”契约优先”(Contract-First)的SOAP服务的开发. 好像没有多少人讨论, 大多数的话题都是围绕xfire, cxf, axis/axis2等主流的Web Service框架.尽管是从事这方面的工作, 不过实际开发中还是公司内部开发的一个Web Service模块,发现与Spring提供的这个模块的构架很像,所以拿出来学习学习.还是先来跑一个类似于Hello Wrold的例子吧.

 

1, 确定SOAP Body中包含的xml

客户端向服务端发出的xml如下:

Java代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <HelloRequest xmlns=”http://www.fuxueliang.com/ws/hello” >  
  3.     Rondy.F  
  4. </HelloRequest>   

 

服务端返回的xml如下:

Java代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <HelloResponse xmlns=”http://www.fuxueliang.com/ws/hello” >  
  3.     Hello, Rondy.F!  
  4. </HelloResponse>  
 

2, 确定WSDL

Java代码  收藏代码
  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.fuxueliang.com/ws/hello”  
  6.     xmlns:tns="http://www.fuxueliang.com/ws/hello/definitions"  
  7.     targetNamespace="http://www.fuxueliang.com/ws/hello/definitions">      
  8.     <wsdl:types>  
  9.     <schema xmlns="htp://www.w3.org/2001/XMLSchema"    
  10.         argetNamespace="http://www.fuxueliang.com/ws/hello">  
  11.         <element name="HelloRequest" type="string" />  
  12.         <element name="HelloResponse" type="string" />  
  13.     </schema>  
  14.     </wsdl:types>  
  15.     <wsdl:message name="HelloRequest">  
  16.         <wsdl:part element="schema:HelloRequest" name="HelloRequest" />  
  17.     </wsdl:message>  
  18.     <wsdl:message name="HelloResponse">  
  19.         <wsdl:part element="schema:HelloResponse" name="HelloResponse" />  
  20.     </wsdl:message>  
  21.     <wsdl:portType name="HelloPortType">  
  22.         <wsdl:operation name="Hello">  
  23.             <wsdl:input message="tns:HelloRequest" name="HelloRequest" />  
  24.             <wsdl:output message="tns:HelloResponse" name="HelloResponse" />  
  25.         </wsdl:operation>  
  26.     </wsdl:portType>  
  27.     <wsdl:binding name="HelloBinding" type="tns:HelloPortType">  
  28.         <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http" />  
  29.         <wsdl:operation name="Hello">  
  30.             <soap:operation soapAction="" />  
  31.             <wsdl:input name="HelloRequest">  
  32.                 <soap:body use="literal" />  
  33.             </wsdl:input>  
  34.             <wsdl:output name="HelloResponse">  
  35.                 <soap:body use="literal" />  
  36.             </wsdl:output>  
  37.         </wsdl:operation>  
  38.     </wsdl:binding>  
  39.     <wsdl:service name="HelloService">  
  40.         <wsdl:port binding="tns:HelloBinding" name="HelloPort">  
  41.             <soap:address location="http://localhost:8080/springws/webservice" />  
  42.         </wsdl:port>  
  43.     </wsdl:service>  
  44. </wsdl:definitions>  
  

 3, 创建一个Web项目, 由于Spring Web Service是基于Spring MVC的, 在web.xml中添加如下servlet, 并在WEB-INF下建立SpringMVC的默认配置文件spring-ws-servlet.xml:

Java代码  收藏代码
  1. <servlet>       
  2.     <servlet-name>spring-ws</servlet-name>        
  3.     <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>  
  4. </servlet>  
  5. <servlet-mapping>  
  6.     <servlet-name>spring-ws</servlet-name>  
  7.     <url-pattern>/*</url-pattern>  
  8. </servlet-mapping>  
 

4, 创建业务方法及具体实现如下:

Java代码  收藏代码
  1. /** 
  2.  * @author Rondy.F 
  3.  *  
  4.  */  
  5. public interface HelloService {  
  6.   
  7.     String hello(String name);  
  8.   
  9. }  
  
Java代码  收藏代码
  1. /** 
  2.  * @author Rondy.F 
  3.  *  
  4.  */  
  5. public class HelloServiceImpl implements HelloService {  
  6.   
  7.     public String hello(String name) {  
  8.         return "Hello, " + name + "!";  
  9.     }  
  10.   
  11. }  
  

5, 实现一个EndPoint来处理接收到的xml及返回xml.当然, Spring Web Service提供了很多抽象的实现, 包括Dom4j, JDom等等.这里我们使用JDK自带的, 需要继承org.springframework.ws.server.endpoint.AbstractDomPayloadEndpoint.

Java代码  收藏代码
  1. /** 
  2.  * @author Rondy.F 
  3.  *  
  4.  */  
  5. public class HelloEndPoint extends AbstractDomPayloadEndpoint {  
  6.   
  7.     /** 
  8.      * Namespace of both request and response. 
  9.      */  
  10.     public static final String NAMESPACE_URI = "http://www.fuxueliang.com/ws/hello";  
  11.   
  12.     /** 
  13.      * The local name of the expected request. 
  14.      */  
  15.     public static final String HELLO_REQUEST_LOCAL_NAME = "HelloRequest";  
  16.   
  17.     /** 
  18.      * The local name of the created response. 
  19.      */  
  20.     public static final String HELLO_RESPONSE_LOCAL_NAME = "HelloResponse";  
  21.   
  22.     private HelloService helloService;  
  23.   
  24.     @Override  
  25.     protected Element invokeInternal(Element requestElement, Document document) throws Exception {        
  26.         Assert.isTrue(NAMESPACE_URI.equals(requestElement.getNamespaceURI()), "Invalid namespace");       
  27.         Assert.isTrue(HELLO_REQUEST_LOCAL_NAME.equals(requestElement.getLocalName()), "Invalid local name");  
  28.         NodeList children = requestElement.getChildNodes();  
  29.         Text requestText = null;  
  30.         for (int i = 0; i < children.getLength(); i++) {  
  31.             if (children.item(i).getNodeType() == Node.TEXT_NODE) {  
  32.                 requestText = (Text) children.item(i);  
  33.                 break;  
  34.             }  
  35.         }  
  36.         if (requestText == null) {  
  37.             throw new IllegalArgumentException("Could not find request text node");  
  38.         }  
  39.   
  40.         String response = helloService.hello(requestText.getNodeValue());  
  41.         Element responseElement = document.createElementNS(NAMESPACE_URI, HELLO_RESPONSE_LOCAL_NAME);  
  42.         Text responseText = document.createTextNode(response);  
  43.         responseElement.appendChild(responseText);  
  44.         return responseElement;  
  45.     }  
  46.   
  47.     public void setHelloService(HelloService helloService) {  
  48.         this.helloService = helloService;  
  49.     }  
  50.   
  51. }  
 

6, 修改配置文件spring-ws-servlet.xml.

Java代码  收藏代码
  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.   
  6.     <bean id="payloadMapping" class="org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping">  
  7.         <property name="endpointMap">  
  8.             <map>  
  9.                 <entry key=”{http://www.fuxueliang.com/ws/hello}HelloRequest” />        
  10.                     <ref bean="helloEndpoint" />  
  11.                 </entry>  
  12.             </map>  
  13.         </property>  
  14.     </bean>  
  15.     <bean id="hello" class="org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition">  
  16.         <property name="wsdl" value="/WEB-INF/hello.wsdl"/>  
  17.     </bean>  
  18.     <bean id="helloEndpoint" class="org.rondy.ws.HelloEndPoint">  
  19.         <property name="helloService" ref="helloService" />  
  20.     </bean>  
  21.     <bean id="helloService" class="org.rondy.service.HelloServiceImpl" />  
  22. </beans>  
   

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

 

7, 客户端(saaj实现)的代码如下:

Java代码  收藏代码
  1. /** 
  2.  *  
  3.  * @author Rondy.F 
  4.  *  
  5.  */  
  6. public class HelloWebServiceClient {  
  7.   
  8.     public static final String NAMESPACE_URI = "http://www.fuxueliang.com/ws/hello";  
  9.   
  10.     public static final String PREFIX = "tns";  
  11.   
  12.     private SOAPConnectionFactory connectionFactory;  
  13.   
  14.     private MessageFactory messageFactory;  
  15.   
  16.     private URL url;  
  17.   
  18.     public HelloWebServiceClient(String url) throws SOAPException, MalformedURLException {  
  19.         connectionFactory = SOAPConnectionFactory.newInstance();  
  20.         messageFactory = MessageFactory.newInstance();  
  21.         this.url = new URL(url);  
  22.     }  
  23.   
  24.     private SOAPMessage createHelloRequest() throws SOAPException {  
  25.         SOAPMessage message = messageFactory.createMessage();  
  26.         SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();  
  27.         Name helloRequestName = envelope.createName("HelloRequest", PREFIX, NAMESPACE_URI);  
  28.         SOAPBodyElement helloRequestElement = message.getSOAPBody().addBodyElement(helloRequestName);  
  29.         helloRequestElement.setValue("Rondy.F");  
  30.         return message;  
  31.     }  
  32.   
  33.     public void callWebService() throws SOAPException, IOException {  
  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.   
  47.     @SuppressWarnings("unchecked")  
  48.     private void writeHelloResponse(SOAPMessage message) throws SOAPException {  
  49.         SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();  
  50.         Name helloResponseName = envelope.createName("HelloResponse", PREFIX, NAMESPACE_URI);  
  51.         Iterator childElements = message.getSOAPBody().getChildElements(helloResponseName);  
  52.         SOAPBodyElement helloResponseElement = (SOAPBodyElement) childElements.next();  
  53.         String value = helloResponseElement.getTextContent();  
  54.         System.out.println("Hello Response [" + value + "]");  
  55.     }  
  56.   
  57.     public static void main(String[] args) throws Exception {  
  58.         String url = "http://localhost:8080/springws";  
  59.         HelloWebServiceClient helloClient = new HelloWebServiceClient(url);  
  60.         helloClient.callWebService();  
  61.     }  
  62. }  
   

几点看法:

1, 从上面代码可以看出, 比较麻烦的部分就是客户端和服务端对xml处理, 当然一部分原因是由于选择了JDK自带的xml处理器.在实际运用中可以考虑xml的绑定工具, 如jibx, castor等等.那么可能的EndPoint实现就只需要实现类似下面的方法:

 

Java代码  收藏代码
  1. protected HelloResponse invokeInternal(HelloRequest request);  
 

2, 看看wsdl的访问方式, 以.wsdl结尾, 而不是?wsdl, 看起来总是不爽, 看了一下源代码,没有显式改变的方法, 看样子只能自己扩展了.而且上例子中还可以以http://localhost:8080/springws/abcdx/hello.wsdl得到wsdl, 哎...

3, 对于客户端, 直接用HttpClient, post到服务端.

 

前行的路标:

1, 毫无疑问, Spring总为你想的很全, 从SpringMVC提供的那么多的Controller就可以看出来.这次也不例外,jibx, castor, xmlBeans, jaxb, xstream全给你准备了

2, EndPointMapping也提供了很多选择,包括method, 还有注解的方式

 

这只是对Spring Web Service学习的一个过程, 有兴趣的可以一起交流一下!后面将根据官方提供的文档来学习一下它所提供的各种功能以及分析一下它的整个流程.

转至http://fuxueliang.iteye.com/blog/175184

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值