JDK 6 內建輕量級 Web Service 伺服器,無需額外安裝 Axis 等第三方框架即可快速開發部署。本文記錄使用 NetBeans 6 建立最簡單 Java Web Service 的完整流程。
package WebServices;
import javax.jws.*;
import javax.xml.ws.Endpoint;
@WebService(targetNamespace = "https://www.blogjava.net/JAVA-HE", serviceName = "HelloService")
public class WSProvider {
@WebMethod(action = "sayHi", operationName = "sayHi")
public String sayHi(@WebParam(name = "MyName") String name) {
return "Hi, " + name;
}
@Oneway
@WebMethod(action = "printSystemTime", operationName = "printSystemTime")
public void printTime() {
System.out.println(System.currentTimeMillis());
}
public static void main(String[] args) {
Thread wsPublisher = new Thread(new WSPublisher());
wsPublisher.start();
}
private static class WSPublisher implements Runnable {
public void run() {
// 需先執行 wsgen 產生支援類別
// wsgen -cp . WebServices.WSProvider
Endpoint.publish("https://localhost:8888/JAVA-HE/WSProvider", new WSProvider());
}
}
}
classes 目錄,執行 wsgen -cp . WebServices.WSProvider 產生支援類別。WSProvider.main() 啟動發布執行緒。https://localhost:8888/JAVA-HE/WSProvider?wsdl 驗證 WSDL 產出。package client;
import net.blogjava.java_he.*;
public class Test {
public static void main(String[] args) {
HelloService hs = new HelloService();
WSProvider ws = hs.getWSProviderPort();
System.out.println(ws.sayHi("hechangmin"));
ws.printSystemTime();
}
}
執行輸出:Hi, hechangmin,代表調用成功。
127.0.0.1 則使用本機 IP 可能無法連線。