当前位置: 首页 > news >正文

一个简单的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. }

相关文章:

  • open cv图片混合
  • C++第五章习题
  • open cv对比度与亮度调节
  • POJ 1905
  • open cv绘制形状与文字
  • open cv均值 中值 高斯 双边高斯 滤波及模糊
  • C语言运算符优先级
  • open cv膨胀与腐蚀
  • 浅谈外链因何而存在?
  • open cv形态学操作
  • 微软发布Surface平板电脑 再度挑战苹果
  • open cv提取水平线与垂直线
  • 用VBScript实现Zip解压缩目录中的所有文件
  • open cv图像上采样与下采样
  • C#中的Main方法
  • HomeBrew常规使用教程
  • Promise初体验
  • Spring Boot快速入门(一):Hello Spring Boot
  • Vue小说阅读器(仿追书神器)
  • 微信小程序--------语音识别(前端自己也能玩)
  • 为视图添加丝滑的水波纹
  • 在Docker Swarm上部署Apache Storm:第1部分
  • 正则学习笔记
  • 智能合约开发环境搭建及Hello World合约
  • 树莓派用上kodexplorer也能玩成私有网盘
  • ​创新驱动,边缘计算领袖:亚马逊云科技海外服务器服务再进化
  • #{}和${}的区别是什么 -- java面试
  • #Z2294. 打印树的直径
  • $$$$GB2312-80区位编码表$$$$
  • (1)bark-ml
  • (3)选择元素——(17)练习(Exercises)
  • (C#)Windows Shell 外壳编程系列9 - QueryInfo 扩展提示
  • (poj1.3.2)1791(构造法模拟)
  • (Redis使用系列) Springboot 实现Redis 同数据源动态切换db 八
  • (Redis使用系列) Springboot 使用redis实现接口Api限流 十
  • (zhuan) 一些RL的文献(及笔记)
  • (二)windows配置JDK环境
  • (每日持续更新)jdk api之StringBufferInputStream基础、应用、实战
  • (三)c52学习之旅-点亮LED灯
  • (四)模仿学习-完成后台管理页面查询
  • (太强大了) - Linux 性能监控、测试、优化工具
  • (一一四)第九章编程练习
  • .babyk勒索病毒解析:恶意更新如何威胁您的数据安全
  • .NET C#版本和.NET版本以及VS版本的对应关系
  • .NET Standard、.NET Framework 、.NET Core三者的关系与区别?
  • .NetCore项目nginx发布
  • .NET序列化 serializable,反序列化
  • //解决validator验证插件多个name相同只验证第一的问题
  • @Autowired注解的实现原理
  • @Data注解的作用
  • @ModelAttribute注解使用
  • @RestControllerAdvice异常统一处理类失效原因
  • [ vulhub漏洞复现篇 ] GhostScript 沙箱绕过(任意命令执行)漏洞CVE-2019-6116
  • [20150629]简单的加密连接.txt
  • [AutoSar NVM] 存储架构