我这里使用的是apache-cxf-2.6.10,下面就以这个版本为介绍
1、从官网上面下载apache-cxf-2.6.10.zip包,然后解压,将下面这些包导入到所建的web工程中。
servlet-api.jar asm-3.3.1.jar cxf-2.6.10.jar //jetty的全部jar jetty-continuation-7.5.4.v20111024.jar jetty-http-7.5.4.v20111024.jar jetty-io-7.5.4.v20111024.jar jetty-security-7.5.4.v20111024.jar jetty-server-7.5.4.v20111024.jar jetty-util-7.5.4.v20111024.jar neethi-3.0.2.jar wsdl4j-1.6.3.jar xmlschema-core-2.0.3.jar geronimo-servlet_2.5_spec-1.1.2.jar commons-logging-1.1.1.jar //客户端调用需要下面这个两个jar woodstox-core-asl-4.2.0.jar stax2-api-3.1.1.jar
2、创建一个对外的接口
package com.cxf.service; import javax.jws.WebService; @WebService public interface HelloWorldCxfService { String sayHello(String username); }
3、实现对外接口的实现类
package com.cxf.service.imp; import javax.jws.WebService; import com.cxf.service.HelloWorldCxfService; @WebService(endpointInterface="com.cxf.service.HelloWorldCxfService") public class HelloWorldCxfServiceImpl implements HelloWorldCxfService { public String sayHello(String username) { System.out.println("Hello,"+username); return "Hello,"+username; } }
4、发布对外接口
package com.cxf.service; import javax.xml.ws.Endpoint; import org.apache.cxf.interceptor.LoggingInInterceptor; import org.apache.cxf.jaxws.EndpointImpl; import com.cxf.service.imp.HelloWorldCxfServiceImpl; public class MyServerInteceptor { public static void main(String[] args) { String address = "http://localhost:7777/hb"; EndpointImpl ep = (EndpointImpl)Endpoint.publish(address, new HelloWorldCxfServiceImpl()); //添加in拦截器 ep.getInInterceptors().add(new LoggingInInterceptor()); //添加out拦截器 ep.getOutInterceptors().add(new LoggingInInterceptor());; System.out.println("发布消息成功"); } }
在浏览器地址栏中输入 http://localhost:7777/hb?wsdl ,如果页面出现一些列的XML格式的字符串,则表示发布成功
5、测试客户端调用代码
5.1 直接在发布server端测试
package com.cxf.client; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; import com.cxf.service.HelloWorldCxfService; public class MyClient { public static void main(String[] args) { JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); String address = "http://localhost:7777/hb"; factory.setServiceClass(HelloWorldCxfService.class); factory.setAddress(address); HelloWorldCxfService service = (HelloWorldCxfService)factory.create(); String result = service.sayHello("huangbiao"); System.out.println("client : " + result); } }
5.2根据CXF的wsdl2java方式在本地生成代码,在另一个工程中测试
package com.cxf.service; import java.net.MalformedURLException; import com.cxf.service.HelloWorldCxfService; import com.cxf.service.imp.HelloWorldCxfServiceImplService; public class Client1 { public static void main(String[] args) throws MalformedURLException { HelloWorldCxfServiceImplService factory = new HelloWorldCxfServiceImplService(); HelloWorldCxfService iservice = factory.getHelloWorldCxfServiceImplPort(); String result = service.sayHello("huangbiao"); System.out.println("client : " + result); } }
备注:在测试客户端的时候需要将上面引入的jar全部引入进工程。