项目结构:
多模块项目:分别为webservice的服务端和客户端:
项目地址:https://github.com/hankuikuide/webservice-demo
一. 服务端
1.POM文件
只需要添加spring boot自带的web service starter: spring-boot-starter-web-services和 wsdl4j
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
2.服务接口
package com.hkk.server.service;
import javax.jws.WebService;
@WebService
public interface BillService {
String getName(String name);
}
3.服务实现
package com.hkk.server.impl;
import com.hkk.server.service.BillService;
import javax.jws.WebService;
@WebService
public class BillServiceImpl implements BillService {
@Override
public String getName(String name) {
return "hello:" + name;
}
}
5. 发布webservice: 这里采用在main方法和中发布webservice:
package com.hkk.server;
import com.hkk.server.impl.BillServiceImpl;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import javax.xml.ws.Endpoint;
@SpringBootApplication
public class ServerApplication {
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
String url = "http://localhost:8082/webservice";
Endpoint.publish(url,new BillServiceImpl());
System.out.println("发布webService成功!");
}
}
注意端口号不能重复。
4.浏览wsdl文件
打开浏览器,输入地址:http://localhost:8082/webservice?wsdl, 显示如下页面,发布成功
二. 客户端
package com.hkk.client;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
public class WebClient {
public static void main(String[] args) {
// 创建动态客户端
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
Client client = dcf.createClient("http://localhost:8082/webservice/BillServiceImpl?wsdl");
Object[] objects = new Object[0];
try {
// invoke("方法名",参数1,参数2,参数3....);
objects = client.invoke("getName", "hkk");
System.out.println("返回数据:" + objects[0]);
} catch (java.lang.Exception e) {
e.printStackTrace();
}
}
}
1.POM文件:只需要添加:cxf-spring-boot-starter-jaxws
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
2.client代码,调用webservice:
package com.hkk.client;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
public class WebClient {
public static void main(String[] args) {
// 创建动态客户端
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
Client client = dcf.createClient("http://localhost:8082/webservice/BillServiceImpl?wsdl");
Object[] objects = new Object[0];
try {
objects = client.invoke("getName", "maple");
System.out.println("返回数据:" + objects[0]);
} catch (java.lang.Exception e) {
e.printStackTrace();
}
}
}