標籤:style blog http ar color os 使用 sp java
最近項目中有用到WebService,於是就研究了一下,但是關於intellij 開發 WebService 的文章極少,要不就是多年以前,於是研究一下,寫這篇博文。純屬記錄,分享,中間有不對的地方,望請指正,下面開始。
首先,開發WebService的伺服器端,不需要藉助任何的其他,JDK就可以搞定,只要在類上標註了@WebService,以及在方法上,標註了@WebMethod方法,就可以認為他是一個WebService。
下面,先顯示一下我的目錄結構:
在server包下的是伺服器端代碼,在client包下的是用戶端代碼。
下面看一下,服務端代碼:
HelloWorldWS.java
1 package server;2 3 /**4 * Created by Lin_Yang on 2014/12/16.5 */6 public interface HelloWorldWS {7 public String sayHello(String name);8 }
這是一個介面。(當然也可以沒有這個介面,效果是一樣的)
HelloWorldImpl.java
package server;import javax.jws.WebMethod;import javax.jws.WebService;/** * Created by Lin_Yang on 2014/12/16. */@WebServicepublic class HelloWorldImpl implements HelloWorldWS { @WebMethod @Override public String sayHello(String name) { String str="歡迎你:"+name; System.out.println(str); return str; }}
注意上面的兩個注釋@WebService 和 @WebMethod
下面就發行就緒這個WebService了
Publish.java
package server;import javax.xml.ws.Endpoint;/** * Created by Lin_Yang on 2014/12/16. */public class Publish { public static void main(String args[]){ Object implementor = new HelloWorldImpl(); String address = "http://localhost:8989/HelloWorld"; //發布到的地址 Endpoint.publish(address, implementor); System.out.println("發布成功"); }}
用戶端的代碼很簡單,這裡就不連篇累牘了。
下面著重說一下用戶端代碼的建立過程。
intellij14 中內建了WebService 的用戶端代碼的實現方式,他是使用的 JAX-WS.廢話不多說,。
在Intellj 的 Tool-->WebServices-->Generate Java Code From WSDL (一看就是根據WSDL文檔產生java代碼了)
隨後應該彈出這個一個提示框。
首先,Web service wsdl url 是指明WSDL文檔的位置,這裡的地址和服務端發布的地址相對應。他也可以不從網路中尋找這個WSDL文檔,也可以從本地尋找。
格式是這樣的:file:/c:/CRMLOYMemberCreateWorkflow.wsdl 指定文檔的地址。
按照的配置,就會在client包中產生這些代碼
下面我們就可以根據這些產生的程式碼,訪問服務端的WebService了
test/client.java
package client.test;import client.HelloWorldImpl;import client.HelloWorldImplService;/** * Created by Lin_Yang on 2014/12/16. */public class Client { public static void main(String args[]){ HelloWorldImplService helloWorldImplService=new HelloWorldImplService(); HelloWorldImpl helloWorld= helloWorldImplService.getHelloWorldImplPort(); String returnStr= helloWorld.sayHello("Crowdsourced Security Testing後覺"); System.out.println(returnStr); }}
服務端顯示
用戶端顯示:
希望可以給大家一些啟示。
intellij 開發webservice