加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 22:51:17 所属栏目:安全 来源:网络整理
导读:服务器端开发 新建一个java工程,写一个接口,加上注解,@WebService和@WebMethod package com.ws.service; import javax.jws.WebMethod; import javax.jws.WebService; @WebService public interface HelloWS { @WebMethod String sayHello(String name);}

服务器端开发

  • 新建一个java工程,写一个接口,加上注解,@WebService和@WebMethod
package com.ws.service;

import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService
public interface HelloWS {
    @WebMethod
    String sayHello(String name);
}
  • 实现类也要加上@WebService注解
package com.ws.service;

import javax.jws.WebService;

@WebService
public 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"));
    }

}

客户端开发完毕

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读