1.什么是webService
web Service也叫XML Web Service,Web服务。可使用开放的xml标准来描述、发布、发现、协调和配置这些应用程序。用于开发分布式的互操作的应用程序。是一种跨编程语言、跨操作系统、跨网络的远程服务器调用技术。
Webservice使用http传输SOAP协议的数据的一种远程调用技术(即系统和系统之间的调用)
什么是webService?说白了就是为了获取我们想要的数据,我们使用服务端发布的接口,从而得到我们想要的数据。
4.开发案例1-天气查询
先定义服务器端:
先定义服务器端:
步骤1: 创建SEI(service Endpoint Interface)接口,即java接口
package server;
public interface WeatherDao {
public String getWeather(String city);
}
步骤2: 创建SEI实现类,在实现类上@WebService注解
package server.impl;
import server.WeatherDao;
import javax.jws.WebService;
@WebService
public class WeatherDaoImpl implements WeatherDao {
public String getWeather(String city) {
if (city.equals("广州")){
return "多云";
}else if (city.equals("天津")){
return "晴朗";
}else if (city.equals("四川")){
return "阵雨";
}else{
return "未知";
}
}
}
步骤3: 发布服务,Endpoint发布服务publish方法,两个参数:服务地址和服务实现类
package server.impl;
import javax.xml.ws.Endpoint;
public class TestServer {
public static void main(String[] args) {
//发布接口
System.out.println("服务器启动");
Endpoint.publish("http://localhost:8080/getWeather",new WeatherDaoImpl());//http://localhost:8080/getWeather?xsdl是访问路径。WSDL阅读方式:从下往上读
}
}
服务端发布完接口后,http://localhost:8080/getWeather?xsdl访问界面及阅读步骤:
注意事项:TestServer 要运行(即服务器运行)http://localhost:8080/getWeather?xsdl被才能访问
以上是服务器端
以下是客户端
客户端编写(也就是指客户端如何使用服务端的接口):
注意:
- 要先发布服务器端服务,服务运行的状态下生成代码
- -s后面有个小点,用于指定源代码生成的目录。点即当前目录。
- 运行客户端必须开启远程服务
第一步: wsimport命令生成客户端代码(通过cmd进入到当前项目的src路径下,
wsimport.exe命令是在jdk的bin目录下)
在cmd中输入如下代码
wsimport -s . http://localhost:8080/getWeather?wsdl
注意事项:wsimport -s . 是固定的,http://localhost:8080/getWeather?wsdl是访问的地址。不要用手打进cmd,要赋值进去。手打可能不会生效。
cmd使用:D:是直接换去D盘,
cd f是去当前文件夹的f文件夹中,
cd…是返回上一级
第二步: 将cmd中编译进f文件夹的.java文件复制进客户端的包中。
第三步:
根据使用说明书(即http://localhost:8080/getWeather?wsdl),使用客户端代码调用服务端
2.1 创建服务视图,视图是从service标签的name属性获取
2.2 获取服务实现类,实现类从portType的name属性获取
2.3 获取查询方法,从portType的operation标签获取
package server;
import server.impl.WeatherDaoImpl;
import server.impl.WeatherDaoImplService;
public class client {
public static void main(String[] args) {
//调用服务器定的接口
//创建xsdl网页中的Service标签中的对象
WeatherDaoImplService service=new WeatherDaoImplService();//WeatherDaoImplService这个类是http://localhost:8080/getWeather?wsdl网页中的service标签的name属性值
//获得服务器的实现类
WeatherDaoImpl port = service.getPort(WeatherDaoImpl.class);//WeatherDaoImpl是http://localhost:8080/getWeather?wsdl网页中portType标签的name属性值
//调用服务器定义的getWeather()方法
String weather = port.getWeather("广州");
System.out.println(weather);
}
}
此次项目的结构图: