Idea實現WebService例項
阿新 • • 發佈:2019-02-15
因為工作需要,資料傳輸部分需要使用webservice實現,經過兩天的研究,實現了一個簡單的例子,具體方法如下。
首先需要新建一個專案,如圖:
下一步點選finish,然後會生成一個webservice專案,在HelloWorld類裡面寫自己的方法,在file下編譯一下這個類,不編譯,idea會提示不通過,編譯後需要將為該服務釋出WSDL檔案,此檔案必須生成,如下圖:
選擇需要釋出的服務
然後部署到TOMCAT,如圖,這裡需要注意的是需要引入這個庫才能正常執行webservice
啟動tomcat後,在瀏覽器中敲入如下程式碼:localhost:8080/services 回車測試webservice是否部署成功:
然後編寫客戶端測試程式碼,如下:
主要程式碼:
服務端:
package example; import javax.jws.WebService; /** * Created by zhangqq on 2016/8/26. */ public class HelloWorld { public String sayTitle(String from) { String result = "title is " + from; System.out.println(result); return result; } public String sayBody(String Other) { String result = "-------------body is-------------- " + Other; System.out.println(result); return result; } public String sayAll(String title,String body) { String result ="--------title:"+title+ "----------------/r/nbody:--------------------------- " + body; System.out.println(result); return result; } }
客戶端:
package test; import org.apache.axis.client.Call; import org.apache.axis.client.Service; import org.apache.axis.utils.StringUtils; import javax.xml.rpc.ServiceException; import java.net.MalformedURLException; /** * Created by zhangqq on 2016/8/29. */ public class WebSvrClient { public static void main(String[] args) { String url = "http://localhost:8080/services/HelloWorldService"; String method = "sayTitle"; String[] parms = new String[]{"abc"}; WebSvrClient webClient = new WebSvrClient(); String svrResult = webClient.CallMethod(url, method, parms); System.out.println(svrResult); } public String CallMethod(String url, String method, Object[] args) { String result = null; if(StringUtils.isEmpty(url)) { return "url地址為空"; } if(StringUtils.isEmpty(method)) { return "method地址為空"; } Call rpcCall = null; try { //例項websevice呼叫例項 Service webService = new Service(); rpcCall = (Call) webService.createCall(); rpcCall.setTargetEndpointAddress(new java.net.URL(url)); rpcCall.setOperationName(method); //執行webservice方法 result = (String) rpcCall.invoke(args); } catch (Exception e) { e.printStackTrace(); } return result; } }
例項地址: