首先,在Eclipse中用maven构建一个quickstart版本的maven项目,并且在pom文件中添加4个依赖,分别是:cxf-rt-frontend-jaxws、cxf-rt-databinding-aegis、cxf-rt-transports-http、cxf-rt-transports-http-jetty,在本次测试时用的版本都是2.5.2,在笔者测试时最高版本升级为2.6.2。以下为本次项目的pom文件中的依赖:
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>2.5.2</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-databinding-aegis</artifactId> <version>2.5.2</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http</artifactId> <version>2.5.2</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http-jetty</artifactId> <version>2.5.2</version> </dependency>
第一步,建立HelloWorld接口,此处的Document应该为W3C的文档形式。
public interface HelloWorld { String sayHi(String text); Document getADocument(); }
第二步,建立HelloWorld的实现类HelloWorldImpl。
public class HelloWorldImpl implements HelloWorld{ public String sayHi(String text) { System.out.println("sayHi called"); return "Hello " + text; } public Document getADocument() { DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; try { db = dbfac.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } Document doc =db.newDocument(); Element carrot = doc.createElement("carrot"); doc.appendChild(carrot); carrot.appendChild(doc.createTextNode("Carrots are roots")); return doc; } }
DocumentBuilderFactory:该类是一个解析器的工厂,包含的解析器可以在XML文档产生一个DOM对象树,是一个工厂类。
DocumentBuilder : 该API在XML文档中包含DOM文档实例。
第三步,建立服务类Server。
HelloWorldImpl hwi = new HelloWorldImpl(); ServerFactoryBean fac = new ServerFactoryBean(); fac.setServiceClass(HelloWorld.class); fac.setAddress("http://localhost:8899/hello"); fac.setServiceBean(hwi); fac.getServiceFactory().setDataBinding(new AegisDatabinding()); fac.create(); System.out.println("Server ready..."); Thread.sleep(5 * 60 * 1000); System.out.println("Server exiting"); System.exit(0); }
该服务首先创建一个服务工厂,然后通过服务工厂设置服务类、服务地址、服务实体,同时把这些服务的参数绑定到该服务中,同时设置一个线程来控制服务启动的时间为1分钟,有效的控制了端口占用问题。
第三步,创建客户端
ClientProxyFactoryBean cfac = new ClientProxyFactoryBean(); if(args != null && args.length>0 && !"".equals(args[0])){ cfac.setAddress(args[0]); }else{ cfac.setAddress("http://localhost:8899/hello"); } cfac.getServiceFactory().setDataBinding(new AegisDatabinding()); HelloWorld client = cfac.create(HelloWorld.class); System.out.println(client.sayHi(System.getProperty("user.name"))); System.out.println("------------------------------"); Document doc = client.getADocument(); Element e = (Element) doc.getFirstChild(); System.out.println(e.getTagName()); Text t = (Text) e.getFirstChild(); System.out.println(t); }
首先获得客户端代理工厂类,通过该类来获绑定务中信息,客户端的服务地址必须和服务端的地址相同,否则无法访问。
到此为止,我们已经成功的书写好了所需要的代码,然后运行server,此处server的启动时间为1分钟,所以在一分钟之类运行客户端,看到如下结果:
Hello Administrator |
------------------------------ |
carrot |
[#text: Carrots are roots] |
本次测试附带源码,读者可以下载。