?? 使用CXF来开发WebService非常的简单,这要感谢apache CXF团队辛勤的工作.下面就我实践CXF的过程分享给大家.
这次的是编程发布WebService方式的完整例子,算是入门级的Hello world.
?? WS服务端:
(1)HelloWorld.java接口
package com.xxx.ws.code.server; import javax.jws.WebService; @WebService public interface HelloWorld { String sayHi(String text); }
?
(2)实现类HelloWorldImpl.java
package com.xxx.ws.code.server.impl; import javax.jws.WebService; import com.xxx.ws.code.server.HelloWorld; @WebService(endpointInterface = "com.xxx.ws.code.server.HelloWorld", serviceName = "HelloWorld") public class HelloWorldImpl implements HelloWorld { public String sayHi(String text) { System.out.println("sayHi called"); return "Hello " + text; } }
?(3)发布web service
package com.xxx.ws.code.server; //import javax.xml.ws.Endpoint; import org.apache.cxf.interceptor.LoggingInInterceptor; import org.apache.cxf.interceptor.LoggingOutInterceptor; import org.apache.cxf.jaxws.JaxWsServerFactoryBean; import com.xxx.ws.code.server.impl.HelloWorldImpl; public class RunCXFServer { protected RunCXFServer() throws Exception { // START SNIPPET: publish System.out.println("Starting Server"); HelloWorldImpl implementor = new HelloWorldImpl(); JaxWsServerFactoryBean svrFactory = new JaxWsServerFactoryBean(); svrFactory.setServiceClass(HelloWorld.class); svrFactory.setAddress("http://localhost:8002/helloWorld"); svrFactory.setServiceBean(implementor); svrFactory.getInInterceptors().add(new LoggingInInterceptor()); svrFactory.getOutInterceptors().add(new LoggingOutInterceptor()); svrFactory.create(); // END SNIPPET: publish } public static void main(String args[]) throws Exception { new RunCXFServer(); System.out.println("Server ready..."); } }
?
(4)运行RunCXFServer
http://localhost:8002/helloWorld?wsdl就可以看到输出的saop envelope了.
?
编写客户端调用WebService
package com.xxx.ws.code.client; //import javax.xml.namespace.QName; //import javax.xml.ws.Service; //import javax.xml.ws.soap.SOAPBinding; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; import org.apache.cxf.interceptor.LoggingInInterceptor; import org.apache.cxf.interceptor.LoggingOutInterceptor; import com.xxx.ws.code.server.HelloWorld; public class RunCXFCodeClient { public static void main(String args[]) throws Exception { JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.getInInterceptors().add(new LoggingInInterceptor()); factory.getOutInterceptors().add(new LoggingOutInterceptor()); factory.setServiceClass(HelloWorld.class); factory.setAddress("http://localhost:8002/helloWorld"); HelloWorld client = (HelloWorld) factory.create(); String reply = client.sayHi("HI"); System.out.println("Server said: " + reply); } }
?