使用Java開發一個非常簡單的Web Service例子

來源:互聯網
上載者:User
1.定義一個Web Service 的介面類

package org.yang.ws;import javax.jws.WebMethod;import javax.jws.WebService;import javax.jws.soap.SOAPBinding;import javax.jws.soap.SOAPBinding.Style;@WebService@SOAPBinding(style=Style.RPC)public interface TimeServer{@WebMethodpublic String getTimeAsString();public long getTimeAsElapsed();}

2.定義一個Web Service介面的實作類別:

package org.yang.ws;import java.util.Date;import javax.jws.WebService;@WebService(endpointInterface="org.yang.ws.TimeServer")public class TimeServerImpl implements TimeServer{public String getTimeAsString(){return new Date().toString();}public long getTimeAsElapsed(){return new Date().getTime();}}

3.發布Web Service

package org.yang.ws;import javax.xml.ws.Endpoint;public class Publisher{public static void main(String[] args){Endpoint.publish("http://127.0.0.1:9876/ts", new TimeServerImpl());System.out.println("successfully!!");}}

4.類比客戶發送請求:

package org.yang.ws;import java.net.URL;import javax.xml.namespace.QName;import javax.xml.ws.Service;public class Test{public static void main(String[] args) throws Exception{URL url = new URL("http://127.0.0.1:9876/ts?wsdl");QName qName = new QName("http://ws.yang.org/", "TimeServerImplService");Service service = Service.create(url, qName);TimeServer eif = service.getPort(TimeServer.class);System.out.println(eif.getTimeAsString());System.out.println(eif.getTimeAsElapsed());}}

5.以wsdl文檔產生的程式碼來調用:

(1)使用wsimport 命令來將wsdl文檔用戶端代碼:

wsimport -p ts -keep http://127.0.0.1:9876/ts?wsdl

(2)調用服務:

package ts;public class Test{public static void main(String[] args) throws Exception{TimeServerImplService service = new TimeServerImplService();TimeServer eif = service.getTimeServerImplPort();System.out.println(eif.getTimeAsString());System.out.println(eif.getTimeAsElapsed());}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.