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 { @WebMethod public String getTimeAsString(); public long getTimeAsElapsed(); }
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(); } }
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!!"); } }
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()); } }