Java 中的 Web Service 分爲基於 SOAP 的和基於 REST 的兩種,下面簡單說一個基於 SOAP 的例子。要使用 JDK6u4 之後的版本才能編譯通過。
先編寫一個 Web Service 的接口:
package com;
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService
public interface TimeServer {
@WebMethod String getTimeAsString();
@WebMethod long getTimeAsElapsed();
}
package com;
import java.util.Date;
import javax.jws.WebService;
@WebService(endpointInterface = "com.TimeServer")
public class TimeServerImpl implements TimeServer {
public String getTimeAsString() { return new Date().toString(); }
public long getTimeAsElapsed() { return new Date().getTime(); }
}
package com;
import javax.xml.ws.Endpoint;
public class TimeServerPublisher {
public static void main(String[ ] args) {
TimeServerImpl tt= new TimeServerImpl();
Endpoint.publish("http://127.0.0.1:9876/ts",tt );
}
}
如果正常啓動,可以用瀏覽器訪問 http://127.0.0.1:9876/ts?wsdl 看到這個 Web Service 的 wsdl 文檔。
轉載http://zhidao.baidu.com/link?url=8QY81dR99QHJn1eNtOkMswopFR122Sl9IJg9s8c_r5h7M2-xtCrHed3ldJdV-NvSZu9ESSAV0sPX_hicxgmbDJOE6WinI9brpHRZPwFeFHe