概述
wsimport是jdk自帶的命令,可以根據wsdl文檔生成客戶端中間代碼,基於生成的代碼編寫客戶端,可以省很多麻煩。
wsimport命令
wsimport的用法
wsimport [options] <WSDL_URI>
比較常用的[options]有:
1. -d <directory>
在指定的目錄生成class文件
2. -clientjar <jarfile>
在當前目錄生成jar文件,結合-d <directory>可以在指定的目錄生成jar文件
3. -s <directory>
在指定的目錄生成java源文件
4. -p <pkg>
指定生成文件的包結構
5. -keep
在生成class文件,或者jar包時,同時保留java源文件
常用的組合
- 在指定的目錄生成指定包結構的java源文件
假設wsdl文檔的uri為http://localhost:6666/service/interpret?wsdl,那么在F:\temp下,生成包結構為cn.ljl.sand.jws.chapter3.client.wsimport的java源文件的命令為:
wsimport -s F:\temp -p cn.ljl.sand.jws.chapter3.client.wsimport http://localhost:6666/service/interpret?wsdl
- 在指定的目錄生成指定包結構的jar文件
假設wsdl文檔的uri為http://localhost:6666/service/interpret?wsdl,那么在F:\temp下,生成包結構為cn.ljl.sand.jws.chapter3.client.wsimport的interpret-wsimport.jar的命令為:
wsimport -d F:\temp -clientjar interpret-wsimport.jar -p cn.ljl.sand.jws.chapter3.client.wsimport http://localhost:6666/service/interpret?wsdl
編寫客戶端
文件分布圖
說明:cn.ljl.sand.jws.chapter3.client.wsimport中的是基於wsimport生成的代碼;cn.ljl.sand.jws.chapter3.client中的是基於生成代碼的客戶端。
使用wsimport生成代碼
指定-p
cn.ljl.sand.jws.chapter3.client.wsimport
核心類介紹
wsimport生成的文件中,有兩個是我們需要了解的,一個是以wsdl文檔的portType元素的name為名的接口,一個是以wsdl文檔的service元素的name為名的類。比如使用上述命令生成的類圖如下:
比較一下,這里生成的InterpretService接口,和服務端的接口是一致的。而InterpretServiceImplService的getInterpretServiceImplPort方法,可以讓我們獲取InterpretService的實例,然后我們就可以像執行本地代碼一樣請求webservice了。
編寫客戶端
創建WSIClient.java,基於生成的代碼訪問服務。
package cn.ljl.sand.jws.chapter3.client; import java.net.MalformedURLException; import java.net.URL; import org.junit.Assert; import org.junit.Test; import cn.ljl.sand.jws.chapter3.client.wsimport.InterpretService; import cn.ljl.sand.jws.chapter3.client.wsimport.InterpretServiceImplService; public class WSIClient { @Test public void test() { InterpretServiceImplService ss = new InterpretServiceImplService(); InterpretService service = ss.getInterpretServiceImplPort(); String chnum = service.interpret(112358); Assert.assertEquals("一一二三五八", chnum); } @Test public void test2() throws MalformedURLException { URL url = new URL("http://localhost:6666/service/interpret?wsdl"); InterpretServiceImplService ss = new InterpretServiceImplService(url); InterpretService service = ss.getInterpretServiceImplPort(); String chnum = service.interpret(112358); Assert.assertEquals("一一二三五八", chnum); } }
說明:
這里提供了兩個測試方法:test使用最簡單的方式;test2考慮到URL可能的變動,所以單獨指定了URL,而這個url,可以根據需要來自配置。
