CXF是Apache的顶级项目,也是目前Java社区中用来实现WebService流行的一个开源框架(尤其是收编了xfire后)。基于CXF可以非常简单地以WebService的方式来实现Java甚至是跨语言的远程调用,CXF的工作原理如图:
CXF对于WebService的服务器端并没做多少封装,它仍然采用目前Java
SE本身的WebService方式,只是提供了一个JaxWsServerFactoryBean类,从而可以在WebService被调用时增加一些 拦截器的处理。客户端方面CXF则增加了封装,以便能够直接以接口的方式来调用远程的WebService,简化了调用WebService的复杂
性,CXF提供的类为JaxWsProxyFactoryBean,通过此类将WebService的接口类以及WebService的地址放入,即可获取对应接口的代理类。
首先导入:org.apache.cxf:apache-cxf:3.1.3的jar包。
服务端代码:
1:接口类代码:
package com.service; import javax.jws.WebService; /** * Created by ryh on 2015/10/9. */ @WebService public interface HelloWorld { public String sayHello(String name); }
注:通过注解@WebService申明为webservice接口
关于@WebService注解说明可看以下文章:
http://blog.sina.com.cn/s/blog_551d2eea0101jwpv.html
package com.service.impl; import com.service.HelloWorld; import javax.jws.WebService; import java.util.Date; /** * Created by ryh on 2015/10/9. */ @WebService(endpointInterface="com.service.HelloWorld",serviceName="HelloWorldWebService") public class HelloWorldImpl implements HelloWorld { @Override public String sayHello(String name) { return "Hello " + name +",it is " + new Date(); } }3:服务端代码:
第一种:可用Endpoint的publish方法发布service
package com.web; import com.service.HelloWorld; import com.service.impl.HelloWorldImpl; import javax.xml.ws.Endpoint; /** * Created by ryh on 2015/10/9. */ public class CxfTest { public static void main(String args[]) { HelloWorld helloWorld = new HelloWorldImpl(); String address = "http://localhost:8080/helloWorld"; //调用Endpoint的publish方法发布web service Endpoint.publish(address, helloWorld); System.out.println("publich success!"); } }
第二种:使用webService客户端代理工厂发布Service
package com.web; import com.service.HelloWorld; import org.apache.cxf.endpoint.Server; import org.apache.cxf.jaxws.JaxWsServerFactoryBean; /** * Created by ryh on 2015/10/9. */ public class CxfTest { public static void main(String args[]) { //创建WebService客户端代理工厂 JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean(); //设置WebService地址 factory.setAddress("http://localhost:8080/helloWorld"); //注册WebService接口 factory.setServiceClass(HelloWorld.class); Server server = factory.create(); server.start(); System.out.println("publich success!"); } }
写完右键run运行显示如图:
在浏览器访问http://localhost:8080/helloWorld?wsdl此地址并显示如下图:
则服务端接口发布成功。
客户端代码:
package com.web; import com.service.HelloWorld; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; /** * Created by ryh on 2015/10/9. */ public class CxfClient { public static void main(String args[]) { //创建WebService客户端代理工厂 JaxWsProxyFactoryBean jwpfb = new JaxWsProxyFactoryBean(); //注册WebService接口 jwpfb.setServiceClass(HelloWorld.class); //设置WebService地址 jwpfb.setAddress("http://localhost:8080/helloWorld"); HelloWorld hw = (HelloWorld) jwpfb.create(); System.out.println(hw.sayHello("ryh")); } }先运行服务端的main方法 再运行客户端代码,后台显示如下:
客户端调用服务端成功。
注:关于webservice原理 可参考以下文章:http://www.blogjava.net/freeman1984/archive/2012/12/25/393439.html