Use Java to develop a simple web service example

Source: Internet
Author: User
1. Define a Web Service Interface Class

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. Define an implementation class for a Web service interface:

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. Publish a 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. Simulate the customer to send the request:

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. Call the code generated in the WSDL document:

(1) Use the wsimport command to convert the WSDL document client code:

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

(2) call the service:

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());}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.