CXF 入门

来源:互联网 发布:linux 开机启动服务器 编辑:程序博客网 时间:2024/05/21 22:48

一 、环境搭建

1). 下载cxf
根据自己环境情况,比如windows平台、linux平台
2) 解压
3) 设置环境变量
比如笔者的环境:
下载文件:apache-cxf-3.1.1.zip
解压在: F:\opensouce\cxf\apache-cxf-3.1.1
环境变量: CXF_HOME = F:\opensouce\cxf\apache-cxf-3.1.1
PATH= %PATH%;%CXF_HOME%/bin

二 、入门例子

使用eclipse来搭建 一个helloword工程
1) 新建工程maven ,比如 cxfEdu
2) 在pom中添加依赖

    <dependency>        <groupId>org.apache.cxf</groupId>        <artifactId>apache-cxf</artifactId>        <version>3.1.1</version>        <type>pom</type>    </dependency>

3) 新建SEI 接口,如 HelloWorld

import javax.jws.WebParam;import javax.jws.WebService;@WebServicepublic interface HelloWorld {    String sayHello(@WebParam(name="text") String text);}

4) 新建SEI 实现接口,如 HelloWorldImpl

import javax.jws.WebParam;import javax.jws.WebService;@WebService(serviceName = "HelloWorld")public class HelloWorldImpl implements HelloWorld {    public String sayHello(@WebParam(name="text")String text) {        System.out.println("sayHello called");        return "Hello " + text +",This is world.";    }}

5) 发布接口

import javax.xml.ws.Endpoint;import demo.cxf.helloworld.HelloWorld;import demo.cxf.helloworld.HelloWorldImpl;public class Server {    public Server() {        System.out.println("Starting Server");        HelloWorld helloWorld = new HelloWorldImpl();        String address = "http://localhost:9000/HelloWorld";        Endpoint.publish(address, helloWorld);    }    public static void main(String[] args) throws Exception {        new Server();        System.out.println("Server ready...");        Thread.sleep(5 * 60 * 1000);        System.out.println("Server exiting");        System.exit(0); }}

6) 访问和调用web service服务

import javax.xml.namespace.QName;import javax.xml.ws.Service;import javax.xml.ws.soap.SOAPBinding;import demo.cxf.helloworld.HelloWorld;public class Client {    //定义服务的服务名称和服务端口    private static final QName SERVICE_NAME = new QName("http://helloworld.cxf.demo/", "HelloWorld");    private static final QName PORT_NAME = new QName("http://helloworld.cxf.demo/", "HelloWorldPort");    public Client() {    }       public static void main(String[] args) throws Exception{        System.out.println("Starting Client");          //用服务名称创建一个服务        Service service = Service.create(SERVICE_NAME);        // 定义Endpoint地址的内容        String endpointAddress = "http://localhost:9000/HelloWorld";        //在服务中增加端口        service.addPort(PORT_NAME, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);        //获取服务类的对象并处理        HelloWorld helloWorld = service.getPort(HelloWorld.class);        System.out.println(helloWorld.sayHello("Rodger "));             System.exit(0);    }}
0 0
原创粉丝点击