最近項目中有用到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. */ @WebService public 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("先知后覺"); System.out.println(returnStr); } }
服務端顯示
客戶端顯示:
希望可以給大家一些啟示。