Spring Webservice实现过程

1、创建service接口

package com.liul.test.spring_ws_test.service;

public interface SayHello {
 public String sayHello(String name);
}

2、创建接口实现(一定要加上service注解)

package com.liul.test.spring_ws_test.service.impl;

import org.springframework.stereotype.Service;

import com.liul.test.spring_ws_test.service.SayHello;
@Service
public class SayHelloImpl implements SayHello {

 public String sayHello(String name) {
  // TODO Auto-generated method stub
  return name+":Hello!";
 }

}

3、创建endpoint

package com.liul.test.spring_ws_test.ws;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

import com.liul.test.spring_ws_test.service.SayHello;

@Endpoint
public class SayHelloEndPoint {
 public static final String NAMESPACE_URI="http://www.liul.com/sayHello";
 public static final String REQUEST_LOCAL_NAME="sayRequest";
 public static final String RESPONSE_LOCAL_NAME = "sayResponse";
 private final SayHello service;
 private final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
 @Autowired
 public SayHelloEndPoint(SayHello service) {
  this.service = service;
 }
 @PayloadRoot(localPart=REQUEST_LOCAL_NAME,namespace=NAMESPACE_URI)
 @ResponsePayload

 public Element handleRequest(@RequestPayload Element requestElement) throws ParserConfigurationException{
     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 echo = service.sayHello(requestText.getNodeValue());

         DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
         Document document = documentBuilder.newDocument();
         Element responseElement = document.createElementNS(NAMESPACE_URI, RESPONSE_LOCAL_NAME);
         Text responseText = document.createTextNode(echo);
         responseElement.appendChild(responseText);
         return responseElement;
 }
}
4、定义schema,say.xsd文件

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="qualified"
        targetNamespace="http://www.liul.com/sayHello"
        xmlns:tns="http://nouse.org">
    <element name="sayRequest" type="string"/>

    <element name="sayResponse" type="string"/>
</schema>

5、修改web.xml

    <servlet>
        <servlet-name>spring-ws</servlet-name>
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
        <init-param>
            <!-- Transform the location attributes in WSDLs -->
            <param-name>transformWsdlLocations</param-name>
            <param-value>true</param-value>
        </init-param>
    </servlet>

    <!-- Map all requests to this servlet -->
    <servlet-mapping>
        <servlet-name>spring-ws</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

6、配置spring-ws-servlet.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sws="http://www.springframework.org/schema/web-services"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <description>
  This web application context contains Spring-WS beans. The beans defined
  in this context are automatically
  detected by Spring-WS, similar to the way Controllers are picked up in Spring
  Web MVC.
    </description>
 <context:component-scan base-package="com.liul.test.spring_ws_test" />
 <sws:annotation-driven />
 <sws:interceptors>
  <bean
   class="org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor">
   <description>
    This interceptor validates both incoming and outgoing message contents
    according to the 'echo.xsd' XML
    Schema file.
            </description>
   <property name="schema" value="/WEB-INF/say.xsd" />
   <property name="validateRequest" value="true" />
   <property name="validateResponse" value="true" />
  </bean>
  <bean
   class="org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor">
   <description>
    This interceptor logs the message payload.
            </description>
  </bean>
 </sws:interceptors>
 <sws:dynamic-wsdl id="say" portTypeName="Echo"
  locationUri="http://localhost:8080/abcd">
  <sws:xsd location="/WEB-INF/say.xsd" />
 </sws:dynamic-wsdl>
</beans>

至此,服务器端配置完成

要点:

1、endpoint类的NAMESPACE_URI与客户端请求文件的xmlns值一致(sayRequest.xml)

     示例定义为:http://www.liul.com/sayHello

2、endpoint里的REQUEST_LOCAL_NAME要和客户端请求文件的根标记一致

     示例定义为:sayRequest

3、客户端的defaultUri必须是可访问的web工程路径

      示例定义为:http://localhost:8080/abcd

4、注:在spring-ws-servlet.xml配置的sws:dynamic-wsdl可不用配置,只是用来在浏览器中查看wsdl,不影响webservice访问

客户端的请求文件(sayRequest.xml)

<?xml version="1.0" encoding="UTF-8"?>
<sayRequest xmlns="http://www.liul.com/sayHello">dabao大宝</sayRequest>         

客户端代码

package org.springframework.ws.samples.echo.client.sws;

import java.io.IOException;
import javax.xml.transform.Source;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import org.springframework.xml.transform.ResourceSource;
import org.springframework.xml.transform.StringResult;

public class EchoClient extends WebServiceGatewaySupport {

    private Resource request;

    public void setRequest(Resource request) {
        this.request = request;
    }

    public void echo() throws IOException {
        Source requestSource = new ResourceSource(request);
        StringResult result = new StringResult();
        getWebServiceTemplate().sendSourceAndReceiveToResult(requestSource, result);
        System.out.println();
        System.out.println("response1:"+result);
        System.out.println();
    }

    public static void main(String[] args) throws IOException {
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml", EchoClient.class);
        EchoClient echoClient = (EchoClient) applicationContext.getBean("sayClient");
        echoClient.echo();
    }

}

猜你喜欢

转载自zzc1684.iteye.com/blog/1983681