Spring Web Service 学习之Hello World篇

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

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代码 <?xml version="1.0" encoding="UTF-8"?>   
  1. <HelloRequest xmlns=”http://www.fuxueliang.com/ws/hello” >   
  2.     Rondy.F   
  3. </HelloRequest>   
<?xml version="1.0" encoding="UTF-8"?><HelloRequest xmlns=”http://www.fuxueliang.com/ws/hello” >	Rondy.F</HelloRequest> 

 

服务端返回的xml如下:

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

 

2, 确定WSDL

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

  

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

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

 

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

Java代码
/**  
  1.  * @author Rondy.F  
  2.  *   
  3.  */  
  4. public interface HelloService {   
  5.   
  6.     String hello(String name);   
  7.   
  8. }  
/** * @author Rondy.F *  */public interface HelloService {	String hello(String name);}

 

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

 

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

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

 

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

Java代码 <?xml version="1.0" encoding="UTF-8"?>   
  1. <beans xmlns="http://www.springframework.org/schema/beans"    
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">   
  4.   
  5.     <bean id="payloadMapping" class="org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping">   
  6.         <property name="endpointMap">   
  7.             <map>   
  8.                 <entry key=”{http://www.fuxueliang.com/ws/hello}HelloRequest” />         
  9.                     <ref bean="helloEndpoint" />   
  10.                 </entry>   
  11.             </map>   
  12.         </property>   
  13.     </bean>   
  14.     <bean id="hello" class="org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition">   
  15.         <property name="wsdl" value="/WEB-INF/hello.wsdl"/>   
  16.     </bean>   
  17.     <bean id="helloEndpoint" class="org.rondy.ws.HelloEndPoint">   
  18.         <property name="helloService" ref="helloService" />   
  19.     </bean>   
  20.     <bean id="helloService" class="org.rondy.service.HelloServiceImpl" />   
  21. </beans>  
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" 	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">	<bean id="payloadMapping" class="org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping">		<property name="endpointMap">			<map>				<entry key=”{http://www.fuxueliang.com/ws/hello}HelloRequest” />							<ref bean="helloEndpoint" />				</entry>			</map>		</property>	</bean>	<bean id="hello" class="org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition">		<property name="wsdl" value="/WEB-INF/hello.wsdl"/>	</bean>	<bean id="helloEndpoint" class="org.rondy.ws.HelloEndPoint">		<property name="helloService" ref="helloService" />	</bean>	<bean id="helloService" class="org.rondy.service.HelloServiceImpl" /></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.  * @author Rondy.F  
  3.  *   
  4.  */  
  5. public class HelloWebServiceClient {   
  6.   
  7.     public static final String NAMESPACE_URI = "http://www.fuxueliang.com/ws/hello";   
  8.   
  9.     public static final String PREFIX = "tns";   
  10.   
  11.     private SOAPConnectionFactory connectionFactory;   
  12.   
  13.     private MessageFactory messageFactory;   
  14.   
  15.     private URL url;   
  16.   
  17.     public HelloWebServiceClient(String url) throws SOAPException, MalformedURLException {   
  18.         connectionFactory = SOAPConnectionFactory.newInstance();   
  19.         messageFactory = MessageFactory.newInstance();   
  20.         this.url = new URL(url);   
  21.     }   
  22.   
  23.     private SOAPMessage createHelloRequest() throws SOAPException {   
  24.         SOAPMessage message = messageFactory.createMessage();   
  25.         SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();   
  26.         Name helloRequestName = envelope.createName("HelloRequest", PREFIX, NAMESPACE_URI);   
  27.         SOAPBodyElement helloRequestElement = message.getSOAPBody().addBodyElement(helloRequestName);   
  28.         helloRequestElement.setValue("Rondy.F");   
  29.         return message;   
  30.     }   
  31.   
  32.     public void callWebService() throws SOAPException, IOException {   
  33.         SOAPMessage request = createHelloRequest();   
  34.         SOAPConnection connection = connectionFactory.createConnection();   
  35.         SOAPMessage response = connection.call(request, url);   
  36.         if (!response.getSOAPBody().hasFault()) {   
  37.             writeHelloResponse(response);   
  38.         } else {   
  39.             SOAPFault fault = response.getSOAPBody().getFault();   
  40.             System.err.println("Received SOAP Fault");   
  41.             System.err.println("SOAP Fault Code :" + fault.getFaultCode());   
  42.             System.err.println("SOAP Fault String :" + fault.getFaultString());   
  43.         }   
  44.     }   
  45.   
  46.     @SuppressWarnings("unchecked")   
  47.     private void writeHelloResponse(SOAPMessage message) throws SOAPException {   
  48.         SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();   
  49.         Name helloResponseName = envelope.createName("HelloResponse", PREFIX, NAMESPACE_URI);   
  50.         Iterator childElements = message.getSOAPBody().getChildElements(helloResponseName);   
  51.         SOAPBodyElement helloResponseElement = (SOAPBodyElement) childElements.next();   
  52.         String value = helloResponseElement.getTextContent();   
  53.         System.out.println("Hello Response [" + value + "]");   
  54.     }   
  55.   
  56.     public static void main(String[] args) throws Exception {   
  57.         String url = "http://localhost:8080/springws";   
  58.         HelloWebServiceClient helloClient = new HelloWebServiceClient(url);   
  59.         helloClient.callWebService();   
  60.     }   
  61. }  
/** *  * @author Rondy.F *  */public class HelloWebServiceClient {	public static final String NAMESPACE_URI = "http://www.fuxueliang.com/ws/hello";	public static final String PREFIX = "tns";	private SOAPConnectionFactory connectionFactory;	private MessageFactory messageFactory;	private URL url;	public HelloWebServiceClient(String url) throws SOAPException, MalformedURLException {		connectionFactory = SOAPConnectionFactory.newInstance();		messageFactory = MessageFactory.newInstance();		this.url = new URL(url);	}	private SOAPMessage createHelloRequest() throws SOAPException {		SOAPMessage message = messageFactory.createMessage();		SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();		Name helloRequestName = envelope.createName("HelloRequest", PREFIX, NAMESPACE_URI);		SOAPBodyElement helloRequestElement = message.getSOAPBody().addBodyElement(helloRequestName);		helloRequestElement.setValue("Rondy.F");		return message;	}	public void callWebService() throws SOAPException, IOException {		SOAPMessage request = createHelloRequest();		SOAPConnection connection = connectionFactory.createConnection();		SOAPMessage response = connection.call(request, url);		if (!response.getSOAPBody().hasFault()) {			writeHelloResponse(response);		} else {			SOAPFault fault = response.getSOAPBody().getFault();			System.err.println("Received SOAP Fault");			System.err.println("SOAP Fault Code :" + fault.getFaultCode());			System.err.println("SOAP Fault String :" + fault.getFaultString());		}	}	@SuppressWarnings("unchecked")	private void writeHelloResponse(SOAPMessage message) throws SOAPException {		SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();		Name helloResponseName = envelope.createName("HelloResponse", PREFIX, NAMESPACE_URI);		Iterator childElements = message.getSOAPBody().getChildElements(helloResponseName);		SOAPBodyElement helloResponseElement = (SOAPBodyElement) childElements.next();		String value = helloResponseElement.getTextContent();		System.out.println("Hello Response [" + value + "]");	}	public static void main(String[] args) throws Exception {		String url = "http://localhost:8080/springws";		HelloWebServiceClient helloClient = new HelloWebServiceClient(url);		helloClient.callWebService();	}}

   

几点看法:

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

 

Java代码 protected HelloResponse invokeInternal(HelloRequest request);  
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学习的一个过程, 有兴趣的可以一起交流一下!后面将根据官方提供的文档来学习一下它所提供的各种功能以及分析一下它的整个流程.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值