Spring与axis结合调用 WebService

yhahaha 2010-06-09

我们使用XFire发布了WebService,现在我们使用axis作为客户端,调用这个服务

因为Web服务是平台无关的,每个WSDL文件即能描述服务的全部信息,我们首先借助axis的WSDL2Java工具,将WSDL文件转化为java类

java-cplib\axis.jar;lib\commons-logging.jar;lib\commons-discovery.jar;lib\jaxrpc.jar;lib\saaj.jar;lib\wsdl4j.jarorg.apache.axis.wsdl.WSDL2Java-v-W-osrc-pdemo.webservice.clienthttp://localhost:8888/BookService?wsdl

pause

生成的代码在/demo/webservice/client目录中

我们观察http://localhost:8888/BookService?wsdl地址的WSDL文件,其中关键部分:

<wsdl:definitions targetNamespace="http://server.webservice.demo">

  <wsdl:service name="BookService">
    <wsdl:port name="BookServiceHttpPort" binding="tns:BookServiceHttpBinding">
      <wsdlsoap:address location="http://localhost:8888/BookService"/>
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>
public static void main(String[] args) 
  throws ServiceException, MalformedURLException, RemoteException {
    // 客户端调用代码符合标准JAX-RPC接口,不会和具体底层框架绑定
    String wsdl = "http://localhost:8888/BookService?wsdl";
    String namespaceUri = "http://server.webservice.demo";
    String serviceName = "BookService";
    String portName = "BookServiceHttpPort";
    QName serviceQN = new QName(namespaceUri, serviceName);
    QName portQN = new QName(namespaceUri, portName);
    ServiceFactory factory = ServiceFactory.newInstance();
    Service srv = factory.createService(new URL(wsdl), serviceQN);
    BookServicePortType service = 
      (BookServicePortType) srv.getPort(portQN, BookServicePortType.class);
    SearchResponse search = service.search(new Search("j2ee"));
    System.out.println(Arrays.toString(search.getOut()));
    
    // 通过Spring JaxRpcPortProxyFactoryBean 取得
    ApplicationContext context =
      new ClassPathXmlApplicationContext("config.xml");
    MyService springService = (MyService) context.getBean("bookService");
    search = springService.search(new Search("j2ee"));
    System.out.println(Arrays.toString(search.getOut()));
  }
<bean id="bookService"   
      class="org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean">
    <!-- 
      BookServicePortType远程调用方法都将抛出RemoteException,可以自定义一个具有
      相同方法签名的接口,不抛出异常。这样客户端不知道自己调用的是Web服务,解耦
    -->
    <property name="serviceInterface" value="demo.webservice.client.MyService" />
    <property name="portInterface" 
        value="demo.webservice.client.BookServicePortType" />
    <property name="wsdlDocumentUrl" 
        value="http://localhost:8888/BookService?wsdl" />
    <property name="namespaceUri" value="http://server.webservice.demo" />
    <property name="serviceName" value="BookService" />
    <property name="portName" value="BookServiceHttpPort" />
  </bean>

相关推荐