使用Apache CXF创建简单Web Service

1.创建HelloWorld 接口类

<textarea cols="50" rows="15" name="code" class="java">package com.googlecode.garbagecan.cxfstudy.helloworld; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; @WebService public interface HelloWorld { public @WebResult(name=&quot;String&quot;)String sayHi(@WebParam(name=&quot;text&quot;) String text); }</textarea>

2.创建HelloWorld实现类

<textarea cols="50" rows="15" name="code" class="java">package com.googlecode.garbagecan.cxfstudy.helloworld; public class HelloWorldImpl implements HelloWorld { public String sayHi(String name) { String msg = &quot;Hello &quot; + name + &quot;!&quot;; System.out.println(&quot;Server: &quot; + msg); return msg; } }</textarea>

3.创建Server端测试类

<textarea cols="50" rows="15" name="code" class="java">package com.googlecode.garbagecan.cxfstudy.helloworld; import org.apache.cxf.jaxws.JaxWsServerFactoryBean; // http://localhost:9000/HelloWorld?wsdl public class Server { public static void main(String[] args) throws Exception { HelloWorld helloWorld = new HelloWorldImpl(); JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean(); factory.setServiceClass(HelloWorld.class); factory.setAddress(&quot;http://localhost:9000/HelloWorld&quot;); factory.setServiceBean(helloWorld); factory.create(); System.out.println(&quot;Server start...&quot;); Thread.sleep(60 * 1000); System.out.println(&quot;Server exit...&quot;); System.exit(0); } }</textarea>

4.创建Client端测试类

<textarea cols="50" rows="15" name="code" class="java">package com.googlecode.garbagecan.cxfstudy.helloworld; import org.apache.cxf.jaxws.JaxWsProxyFactoryBean; public class Client { public static void main(String[] args) { JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.setServiceClass(HelloWorld.class); factory.setAddress(&quot;http://localhost:9000/HelloWorld&quot;); HelloWorld helloworld = (HelloWorld) factory.create(); System.out.println(helloworld.sayHi(&quot;kongxx&quot;)); System.exit(0); } }</textarea>

5.测试

首先运行Server类来启动Web Service服务,然后访问http://localhost:9000/HelloWorld?wsdl地址来确定web service启动正确。
运行Client测试类,会在命令行输出Hello kongxx!的message。

 

 

 

你可能感兴趣的:(使用Apache CXF创建简单Web Service)