WebService
基于jdk实现服务端客户端:
发布服务:
1.开发接口
2.开发接口实现类 @WebService
3.发布服务 EndPoint.publish(“url”,实现类)
访问服务:
核心要点:一份服务的说明书 url?wsdl
<service name=" ">
在wsdl中找到这个标签,根据这个名称获取到服务试图对象
<portType name=" ">
找到这个标签,根据服务视图对象的getPort方法,
结合这个名称,获取到实现类对象(后面有例子)
<operation name=" ">
根据实现类对象来操作相关的方法
新建简单的Java项目
实现服务端:
接口类:
package com.example;
public interface IWeatherService {
public String query(String cityName);
public String other();
}
实现类:
package com.example;
import javax.jws.WebService;
@WebService
public class WeatherService implements IWeatherService {
@Override
public String query(String cityName){
System.out.println("查询"+cityName);
return "大晴天";
}
@Override
public String other(){
return "其他方法";
}
}
发布类:
package com.webservice;
import com.example.WeatherService;
import javax.xml.ws.Endpoint;
public class main {
public static void main(String[] args) {
Endpoint.publish("http://localhost:8080/weatherService",new WeatherService());
System.out.println("发布成功");
}
}
浏览器访问:http://localhost:8080/weatherService?wsdl
实现访问服务:
新建一个java项目:
打开cmd命令行,进入新建项目文件下:
输入wsimport -s . url?wsdl
如图:
生成客户端代码
新建类访问服务:
package com.client;
import com.example.WeatherService;
import com.example.WeatherServiceService;
public class Client1 {
public static void main(String[] args) {
//创建服务视图对象 wsdl中<service name>
WeatherServiceService service = new WeatherServiceService();
//获取服务的实现类 wsdl中<portType name>
WeatherService port = service.getPort(WeatherService.class);
//调用方法 在<portType 标签下面有<operation name="query">
String query = port.query("北京");
System.out.println(query);
//调用新方法
String other = port.other();
System.out.println(other);
}
}
结果:
客户端:
服务端: