cxf+spring發布webservice和調用

jopen 9年前發布 | 61K 次閱讀 WEB服務/RPC/SOA WebService

項目所需jar包:http://url.cn/V6RvIw 因為我用到了httpclient,所以里面包含了httpclient的jar包。

建項目什么就不說了。

直接上代碼說接口:

寫一個demo接口

package cn.cxf.demo;

import javax.jws.WebService;

@WebService
public interface Demo {
    String sayHi(String text);
}

然后就需要實現它嘍

targetNamespace 是指向接口的包路徑

package cn.cxf.demo.impl;

import javax.jws.WebService;

import cn.cxf.demo.Demo;
@WebService(endpointInterface="cn.cxf.demo.Demo", serviceName="DemoService", targetNamespace="http://demo.cxf.cn/")
public class DemoImpl implements Demo {

    @Override
    public String sayHi(String text) {
        return "Hi ! " + text;
    }

}

在src目錄下添加applicationContext.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:jaxws="http://cxf.apache.org/jaxws"
    xsi:schemaLocation="
 http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans.xsd 
 http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
 
    <import resource="classpath:META-INF/cxf/cxf.xml" />
    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

    <!-- 測試接口    -->
    <jaxws:endpoint id="demoService"
        implementor="cn.cxf.demo.impl.DemoImpl" 
        address="/DemoService" />

</beans>

再修改下web.xml文件就搞定了~(在web.xml添加如下內容就可以了)

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>CXFServlet</servlet-name>
    <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>CXFServlet</servlet-name>
    <url-pattern>/ws/*</url-pattern>
  </servlet-mapping>

發布一下,訪問 http://localhost:8080/cxfdemo/ws 就可以看到接口已經發布成功了。

調用接口就更簡單了

如果只是單純的調用接口的話只需要4個jar包就可以了:

cxf-2.4.3.jar

neethi-3.0.1.jar

wsdl4j-1.6.2.jar

xmlschema-core-2.0.1.jar

可以從上面的jar包里挑選。

調用代碼如下:

package cn.cxf.test;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;

public class CXFWSTest {
    public static void main(String[] args) throws Exception {
        JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();
        Client client = factory.createClient("http://localhost:8080/cxfdemo/ws/DemoService?wsdl");
        Object[] objs = client.invoke("sayHi", "阿福");
        System.out.println(objs[0].toString());
    }
}

哈哈,是不是很簡單。

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!