WebService(1)——使用JDK开发WebService

来源:互联网 发布:西瓜影音播放网络文件 编辑:程序博客网 时间:2024/06/05 14:45

服务器端开发

  • 新建一个java工程,写一个接口,加上注解,@WebService和@WebMethod
package com.ws.service;import javax.jws.WebMethod;import javax.jws.WebService;@WebServicepublic interface HelloWS {    @WebMethod    String sayHello(String name);}
  • 实现类也要加上@WebService注解
package com.ws.service;import javax.jws.WebService;@WebServicepublic class HelloWSImpl implements HelloWS {    @Override    public String sayHello(String name) {        return "hello "+name;    }}
  • 写一个main方法,使用Endpoint来发布webservice
package com.ws.main;import javax.xml.ws.Endpoint;import com.ws.service.HelloWSImpl;public class Main {    public static void main(String[] args) {        //必须写本地IP        String address = "http://172.17.202.155:9999/ws01/hellows";        Endpoint.publish(address , new HelloWSImpl());        System.out.println("发布成功");    }}

这里写图片描述

运行main之后,可以看到上图箭头的位置并没有变灰,说明程序还在运行,它正在等待被访问

  • 用浏览器查看wsdl文档,路径是http://172.17.202.155:9999/ws01/hellows?wsdl
    这里写图片描述

  • 在eclipse工具栏有一个webservice浏览器,我们使用它来测试一下
    这里写图片描述

  • 打开webservice浏览器后,按下图步骤,输入url,点击go
    这里写图片描述

  • 然后可以测试我们发布的接口了
    这里写图片描述

客户端开发

  • 新建一个java工程作为客户端
  • 打开一个cmd命令行
    这里写图片描述

  • 在命令行中进入客户端项目的src所在目录,我们需要在这里使用命令生成客户端代码,命令是:wsimport -keep url。url是我们发布的webservice的url加上?wsdl,回车,自动生成代码

  • 在eclipse中刷新客户端项目,就能看到自动生成的代码了
    这里写图片描述

  • 写一个main调用webservice

package com.ws.service.client.test;import com.ws.service.HelloWSImpl;import com.ws.service.HelloWSImplService;public class Main {    public static void main(String[] args) {        // 调用webservice        HelloWSImplService factory = new HelloWSImplService();        HelloWSImpl helloWS = factory.getHelloWSImplPort();        System.out.println(helloWS.sayHello("tom"));    }}

客户端开发完毕

原创粉丝点击