Web Service就是为了使原来各孤立的站点之间的信息能够相互通信、共享而提出的一种接口。
一,发布一个webservice服务(手动编写,jdk原生)
1,编写实体类
import lombok.Data;
import java.io.Serializable;
@Data
@SuppressWarnings("serial")
public class User implements Serializable {
protected Integer age;
protected String email;
protected Long id;
protected String name;
protected String sex;
}
2,编写服务接口
import javax.jws.WebParam;
import javax.jws.WebService;
import java.util.List;
@WebService
public interface HelloWorld {
String sayHi(@WebParam(name="text")String text);
String sayHiToUser(User user);
String[] SayHiToUserList(List<User> userList);
}
3,服务实现类
import javax.jws.WebParam;
import javax.jws.WebService;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@WebService(endpointInterface= "com.example.webservice.service2.HelloWorld",serviceName="HelloWorld")
public class HelloWorldImpl implements HelloWorld {
Map<Integer, User> users = new LinkedHashMap<Integer, User>();
public String sayHi(@WebParam(name = "text") String text) {
return "Hello哦呀h,你好"+text;
}
public String sayHiToUser(User user) {
users.put(users.size()+1, user);
return "Hello哦呀h,你好"+user.getName();
}
public String[] SayHiToUserList(List<User> userList) {
String[] result = new String[userList.size()];
int i = 0;
for(User u:userList){
result[i] = "Hello哦呀h,你好" + u.getName();
i++;
}
return result;
}
}
4,服务启动类(启动则发布服务,浏览器查看是否发布成功)
import javax.xml.ws.Endpoint;
public class webServiceApp {
public static void main(String[] args) {
System.out.println("web Hello service start");
com.example.webservice.service2.HelloWorldImpl implementor = new HelloWorldImpl();
String address = "http://localhost:8080/helloWorld";
Endpoint.publish(address, implementor);
System.out.println("web Hello service started");
}
}
5,编写客户端访问
import com.example.webservice.service2.HelloWorld;
import com.example.webservice.service2.User;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
public class HelloWorldClient {
/**
* @param args
*/
public static void main(String[] args) {
//首先右键run as 运行com.hsy.server.webServiceApp类,然后再运行这段客户端代码
JaxWsProxyFactoryBean jwpfb = new JaxWsProxyFactoryBean();
jwpfb.setServiceClass(HelloWorld.class);
jwpfb.setAddress("http://localhost:8080/helloWorld");
HelloWorld hw = (HelloWorld) jwpfb.create();
User user = new User();
user.setName("马克思");
user.setEmail("怀念马克思");
System.out.println(hw.sayHiToUser(user)+"成功");
}
}
打印结果:Hello哦呀h,你好马克思成功
二,使用工具自动生成客户端代码
1,下载apache cxf的包,如apache-cxf-2.7.10.zip。Apache CXF -- Download
2,配置环境变量到 Path E:\ .... \bin 如:E:\configuration\apache-cxf-3.3.11\bin
3,在\bin下进入cmd 输入wsdl2java,如果有提示usage,就表明配置成功
4,客户端代码生成命令: wsdl2java -d 生成路径 -client 服务发布地址 如:
wsdl2java -d E:\play\swagger-example\src\main\java\com\example\cxf\client2\generate\client -client http://localhost:8080/helloWorld?wsdl