CXF总结

CXF总结

如何来用cxf结合spring开发webservice接口。by@wangkun

下载cxf

建两个java web project并引入cxf相关jar包

webservice服务端:

webservice客户端:

webService服务端

开始,写一个service interface

package com.webservice.server.wangkun;

/**
* Created by wangkun on 2015/9/21.
*/
import javax.jws.WebService;

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

接着,写我们的实现类:

package com.webservice.server.wangkun;

/**
* Created by wangkun on 2015/9/21.
*/
import javax.jws.WebService;

@WebService(endpointInterface = "com.webservice.server.wangkun.HelloWorld")
public class HelloWorldImpl implements HelloWorld {

public String sayHi(String text) {
System.out.println("sayHi called");
return "Hello " + text;
}
}

声明server beans

CXF包含在Spring的“好XML”的支持。对于JAX-WS,建一个 jaxws:endpoint bean服务器端的endpoint。
在WEB-INF目录下的CXF-servlet.xml文件:




<jaxws:endpoint id="helloWorld" implementor="com.webservice.server.wangkun.HelloWorldImpl" address="/HelloWorld"/>

如果你想弹性的引用bean可以这样写:


<jaxws:endpoint id="helloWorld" implementor="#hello" address="/HelloWorld" />

  • ID指定Spring上下文的bean的ID。
  • implementor是指实现类
  • address 是指请求路径

设置Servlet(web.xml)




contextConfigLocation
/WEB-INF/cxf-servlet.xml


org.springframework.web.context.ContextLoaderListener


CXFServlet
org.apache.cxf.transport.servlet.CXFServlet


CXFServlet
/webService/*

访问

webService客户端

利用cxf的生成工具生成客户端相关类

  1. 把cxf的可执行目录配置到系统环境变量下:

  2. 打开cmd,cd到wsdl文档所在的目录(该wsdl文档是服务端所产生的),执行命令
    wsdl2java wsdl2java F:\webservice_project\cxfClient\src\HelloWorld.wsdl

  3. 效果,可以看到生成的客户端代码

像endpoint用于服务端一样,在客户端使用client,创建client-beans.xml文件









编写测试类:

package com.webservice.test;

import com.webservice.server.wangkun.HelloWorld;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public final class Client {
private Client() {
}
public static void main(String args[]) throws Exception {
// START SNIPPET: client
ClassPathXmlApplicationContext context
= new ClassPathXmlApplicationContext(new String[] {"client-beans.xml"});
HelloWorld client = (HelloWorld)context.getBean("client");
String response = client.sayHi("Joe");
System.out.println("Response: " + response);
System.exit(0);
// END SNIPPET: client
}
}

测试结果

如果出现如下结果,说明客户端测试成功。

如果需要源码请加qq:398121505 或者给我留言,谢谢!

posted @ 2015-09-21 16:18  合肥房屋托管  阅读(681)  评论(0)    收藏  举报