webService初探

  1. 定义一个接口
    import javax.jws.WebService;

      @WebService
    public interface IMyService {

     public int add(int a, int b);

     public int minus(int a, int b);
    }
  2. 实现类
    import javax.jws.WebService;

    @WebService(endpointInterface="com.gcflower.webservice.service.IMyService")
    public class MyService implements IMyService {

        @Override
        public int add(int a, int b) {
            System.out.println("a+b="+(a+b));
            return a+b;
        }

        @Override
        public int minus(int a, int b) {
            System.out.println("a-b="+(a-b));
            return a-b;
        }

    }
  3. 发布
    import javax.xml.ws.Endpoint;

    public class MyServer {

        public static void main(String[] args) {
            String address = "http://localhost:8888/ns";
            //发表服务,成功后在浏览器输入address可访问,输入http://localhost:8888/ns?wsdl可访问wsdl的xml格式的文件
            Endpoint.publish(address, new MyService());
        }
    }
  4. 客户端

    import java.net.MalformedURLException;
    import java.net.URL;

    import javax.xml.namespace.QName;
    import javax.xml.ws.Service;

    public class TestClient {

        public static void main(String[] args) {
            try {
                URL url = new URL("http://localhost:8888/ns?wsdl");
                QName sname = new QName("http://service.webservice.gcflower.com/","MyServiceService");
                //通过url地址和wsdl文件中的targetNamespace和name属性的值创建service
                Service service = Service.create(url, sname);
                //获取端口对象
                IMyService ms = service.getPort(IMyService.class);
                System.out.println(ms.add(20, 40));
                
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
    }
  5. 在dos命令行导出wsdl
    D:\>wsimport -d d:/test/webservice/01/ -keep -verbose http://localhost:8888/ns?wsdl

    wsimpor:命令

    d:/test/webservice/01/:导出的目录

    -keep:生成源码

    -verbose:显示详细信息

    http://localhost:8888/ns?wsdl:服务地址

  在导出的文件中生成了许多其他文件,将生成文件copy到项目的src目录下,新建一个client,使用如下方式也可访问:
  public class TestClient {

    public static void main(String[] args) {
        //新生成的类
        MyServiceService mss = new MyServiceService();
        IMyService ms = mss.getMyServicePort();
        System.out.println(ms.add(40, 50));
    }
    
}


原文地址:https://www.cnblogs.com/charleszhang1988/p/3107244.html