CXF下載地址:http://cxf.apache.org/download.html
解壓後可以看到lib、bin、docs等目錄。在lib有我們需要的jar包。
在eclipse中創建一個java項目,並引入lib下面的包
創建創建一個接口ICaculateService
import javax.jws.WebParam;
import javax.jws.WebService;
@WebService
public interface ICaculateService {
public String getName(@WebParam(name="name")String name);
}
在創建CaculateService類來實現ICaculateService接口
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style=Style.RPC)
public class CaculateService implements ICaculateService {
public String getName(@WebParam(name="name")String name) {
return "chenbin";
}
}
接下來部署WebService
public class DeployWebService {
public static void deployService() {
System.out.println("server start ...");
ICaculateService service = new CaculateService();
String addresString = "http://localhost:9000/caculate";
Endpoint.publish(addresString, service);
}
public static void main(String[] args) throws InterruptedException {
deployService();
System.out.println("server ready ...");
Thread.sleep(1000*60);
System.out.println("server exiting");
System.exit(0);
}
}
WebService發佈好之後,就創建一個客戶端來調用這個服務。在同一個項目中,創建Client類
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
public class Client {
public static void main(String[] args) {
JaxWsProxyFactoryBean factory1 = new JaxWsProxyFactoryBean();
factory1.setServiceClass(ICaculateService.class);
factory1.setAddress("http://localhost:9000/caculate");
ICaculateService service = (ICaculateService) factory1.create();
System.out.println(service.getName(""));
}
}
我們也可以新建一個項目來調用剛剛發佈的WebService。需要把ICaculateService重寫一遍,並且命名空間也要相同。代碼和Client類是一樣的。