Java SE 6 內建 JAX-WS 運行時,配合 Eclipse IDE 與 Ant,可輕鬆建立無需應用伺服器的獨立 Web Service 服務端。本教程逐步示範環境配置、專案建立、服務實作、wsgen 代碼生成、Endpoint.publish 發布、WSDL 驗證與 Web Services Explorer 測試。
wsServerExample,使用專案專屬 JRE (Java SE 6)。com.myfirst.wsServer。SayHello(無 main),貼上服務實作:package com.myfirst.wsServer;
import javax.jws.WebService;
@WebService
public class SayHello {
private static final String SALUTATION = "Hello";
public String getGreeting(String name) {
return SALUTATION + " " + name;
}
}
@WebService 註解標記為 Web Service 端點,Java SE 6 運行時掃描並啟用。
build.xml:<project default="wsgen">
<target name="wsgen">
<exec executable="wsgen">
<arg line="-cp ./bin -keep -s ./src -d ./bin com.myfirst.wsServer.SayHello"/>
</exec>
</target>
</project>
build.xml → Run As → Ant Build,Console 顯示 BUILD SUCCESSFUL。com.myfirst.wsServer.jaxws 套件出現 GetGreeting、GetGreetingResponse、SayHelloService 等 JAX-WS 工件類。wsgen 讀取端點類,生成 WSDL 所需的所有可攜式工件(請求/回應 Bean、Service 類等)。
RunService(含 main 方法):package com.myfirst.wsServer;
import javax.xml.ws.Endpoint;
public class RunService {
public static void main(String[] args) {
System.out.println("SayHello Web Service started.");
Endpoint.publish("https://localhost:8080/wsServerExample", new SayHello());
}
}
Endpoint.publish 為 Java SE 6 新增 API,單行代碼完成 HTTP 端點發布與 WSDL 動態生成。
https://localhost:8080/wsServerExample?wsdl,顯示完整 WSDL 文檔。getGreeting → Add 參數行 → 輸入 "Fiona" → Go。return (string): Hello Fiona,驗證成功。下篇將建立獨立客戶端調用此服務,並示範 SOAP 訊息監控。