CXF-01: WebService的第一个例子

HelloWorld.java:

1 package com.war3.ws;
2 
3 import javax.jws.WebService;
4 
5 @WebService
6 public interface HelloWorld {
7 
8     String sayHi(String name);
9 }

HelloWorldWS.java:

 1 package com.war3.ws.impl;
 2 
 3 import javax.jws.WebService;
 4 import com.war3.ws.HelloWorld;
 5 
 6 @WebService(endpointInterface="com.war3.ws.HelloWorld")
 7 public class HelloWorldWS implements HelloWorld {
 8 
 9     @Override
10     public String sayHi(String name) {
11         return name+",你好!";
12     }
13 
14 }

ServerMain.java:

 1 package com.war3.ws.server;
 2 
 3 import javax.xml.ws.Endpoint;
 4 
 5 import com.war3.ws.HelloWorld;
 6 import com.war3.ws.impl.HelloWorldWS;
 7 
 8 public class ServerMain {
 9 
10     public static void main(String[] args) {
11         HelloWorld hw = new HelloWorldWS();
12         Endpoint.publish("http://localhost:8080/hello", hw);
13         System.out.println("WebService暴露服务成功!");
14     }
15 }

运行ServerMain.java,控制台打印"WebService暴露服务成功!"。

浏览器输入:http://localhost:8080/hello?wsdl,回车得到:

 1 <wsdl:definitions xmlns:ns1="http://ws.war3.com/" xmlns:ns2="http://schemas.xmlsoap.org/wsdl/soap/http" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://impl.ws.war3.com/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="HelloWorldWSService" targetNamespace="http://impl.ws.war3.com/">
 2 <wsdl:import location="http://localhost:8080/hello?wsdl=HelloWorld.wsdl" namespace="http://ws.war3.com/"></wsdl:import>
 3 <wsdl:binding name="HelloWorldWSServiceSoapBinding" type="ns1:HelloWorld">
 4 <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
 5 <wsdl:operation name="sayHi">
 6 <soap:operation soapAction="" style="document"/>
 7 <wsdl:input name="sayHi">
 8 <soap:body use="literal"/>
 9 </wsdl:input>
10 <wsdl:output name="sayHiResponse">
11 <soap:body use="literal"/>
12 </wsdl:output>
13 </wsdl:operation>
14 </wsdl:binding>
15 <wsdl:service name="HelloWorldWSService">
16 <wsdl:port binding="tns:HelloWorldWSServiceSoapBinding" name="HelloWorldWSPort">
17 <soap:address location="http://localhost:8080/hello"/>
18 </wsdl:port>
19 </wsdl:service>
20 </wsdl:definitions>

然后我们再新建一个Java工程WebService_Client:

利用wsdl2java命令和wsdlurl参数,我们在src目录下生成了一些代码:

然后我们写一个类ClientMain.java:

 1 package com.war3.ws.client;
 2 
 3 import com.war3.ws.HelloWorld;
 4 import com.war3.ws.impl.HelloWorldWSService;
 5 
 6 public class ClientMain {
 7 
 8     public static void main(String[] args) {
 9         HelloWorldWSService factory = new HelloWorldWSService();
10         HelloWorld hw = factory.getHelloWorldWSPort();
11         System.out.println(hw.sayHi("tom"));
12     }
13 }

运行代码,控制台输出“tom,你好!”。

 

posted on 2015-11-26 01:16  confirmCname  阅读(222)  评论(0编辑  收藏  举报

导航