本文提供了一個使用Java如何開發(fā)基于SOAP的Web Services,其客戶端可以是Perl、Ruby、Python或Java等。
Java SE 6封裝了JAX-WS(Java API for XML-WebServices),而JAX-WS同時支持基于SOAP的Web服務(wù)和REST風(fēng)格的Web服務(wù)。JAX-WS通??珊唽憺镴WS,當(dāng)前,JWS的版本為2.x。
基于SOAP的Web服務(wù)可用單個Java類的實現(xiàn),但是最好是用“接口+實現(xiàn)”的方式來實現(xiàn)最佳。
Web服務(wù)的接口稱為SEI,即Service Endpoint Interface;
而Web服務(wù)的實現(xiàn)稱為SIB,即Service Implementation Bean。
SIB可以是一個POJO,也可以是無狀態(tài)的會話EJB。本文的SIB是普通Java類,通過JDK 6的類庫即可實現(xiàn)Web服務(wù)的發(fā)布。
代碼1:服務(wù)接口類SEI
- package myweb.service;
- import javax.jws.WebService;
- import javax.jws.WebMethod;
- import javax.jws.soap.SOAPBinding;
- import javax.jws.soap.SOAPBinding.Style;
- @WebService
- @SOAPBinding(style=Style.RPC)
- public interface TimeServer {
- @WebMethod
- String getTimeAsString();
- @WebMethod
- long getTimeAsElapsed();
- }
代碼2:服務(wù)實現(xiàn)類SIB
- package myweb.service;
- import java.text.DateFormat;
- import java.util.Date;
- import javax.jws.WebService;
-
- @WebService(endpointInterface = "myweb.service.TimeServer")
- public class TimeServerImpl implements TimeServer {
-
-
-
-
- public long getTimeAsElapsed() {
- return new Date().getTime();
- }
-
-
-
-
- public String getTimeAsString() {
- Date date = new Date();
- DateFormat df = DateFormat.getDateInstance();
- return df.format(date);
- }
- }
代碼3:服務(wù)發(fā)布類Publisher
- package myweb.service;
- import javax.xml.ws.Endpoint;
-
- public class TimeServerPublisher {
- public static void main(String[] args){
-
-
- Endpoint.publish("http://127.0.0.1:10100/myweb", new TimeServerImpl());
- }
- }
編譯以上代碼:
javac myweb/service/*.java
運行服務(wù):
java myweb/service/TimeServerPublisher
在瀏覽器地址欄輸入:
http://localhost:10100/myweb?wsdl
顯示如下圖所示:
也可編寫客戶端代碼測試服務(wù)。
Java客戶端:
- package myweb.client;
- import javax.xml.namespace.QName;
- import javax.xml.ws.Service;
- import java.net.URL;
- import myweb.service.*;
- public class TimeClient {
- public static void main(String[] args) throws Exception{
- URL url = new URL("http://localhost:10100/myweb?wsdl");
-
-
- QName qname = new QName("http://service.myweb/","TimeServerImplService");
-
- Service service = Service.create(url, qname);
-
- TimeServer eif = service.getPort(TimeServer.class);
- System.out.println(eif.getTimeAsString());
- System.out.println(eif.getTimeAsElapsed());
- }
- }
運行客戶端,顯示結(jié)果如下:
2009-12-21
1261402511859
也可用Ruby編寫客戶端,如下:
-
-
-
- require 'soap/wsdlDriver'
-
- wsdl_url = 'http://127.0.0.1:10100/myweb?wsdl'
-
-
- service = SOAP::WSDLDriverFactory.new(wsdl_url).create_rpc_driver
-
-
- service.wiredump_file_base = 'soapmsgs'
-
-
- result1 = service.getTimeAsString
- result2 = service.getTimeAsElapsed
-
-
- puts "Current time is: #{result1}"
- puts "Elapsed milliseconds from the epoch: #{result2}"
運行結(jié)果相同!