此实例测试CXF支持的数据类型
Student.java实体类
public class Student {
private int id;
private String name;
private float price;
//...省略getter setter方法
public Student() {//无参构造方法
super();
}
}
DataTypeWS.java接口
@WebService
public interface DataTypeWS {
@WebMethod
public boolean add(Student student);
@WebMethod
public Student getStudentById(int id);
@WebMethod
public List<Student> getStudentsByPrice(float price);
@WebMethod
public Map<Integer, Student> getAllStudentsMap();
}
DataTypeWSImpl.java实现接口
@WebService
public class DataTypeWSImpl implements DataTypeWS{
@Override
public boolean add(Student student) {
System.out.println("Server add " + student);
return false;
}
@Override
public Student getStudentById(int id) {
System.out.println("Server getStudentById " + id);
return new Student(id, "umgsai", 15000);
}
@Override
public List<Student> getStudentsByPrice(float price) {
System.out.println("Server getStudentsByPrice " + price);
List<Student>students = new ArrayList<Student>();
students.add(new Student(1, "Tom", price + 1));
students.add(new Student(2, "Tom", price + 2));
students.add(new Student(3, "Tom", price + 3));
return students;
}
//测试中Map的使用出现异常,暂未解决。可能是由于JDK的版本造成的,测试的时候使用了JDK8
@Override
public Map<Integer, Student> getAllStudentsMap() {
System.out.println("Server getAllStudentsMap ");
Map<Integer, Student>map = new HashMap<Integer, Student>();
map.put(1, new Student(1, "umgsai", 15000));
map.put(2, new Student(2, "umgsai2", 16000));
map.put(3, new Student(3, "umgsai3", 17000));
return map;
}
}
发布服务
public class WSServer {
public static void main(String[] args) {
String address = "http://192.168.13.232:8084/ws_cxf/datatype";
Endpoint.publish(address, new DataTypeWSImpl());
System.out.println("服务发布成功");
}
}
可以在浏览器中通过 http://192.168.13.232:8084/ws_cxf/datatype?wsdl来查看发布的服务
使用CXF自带的工具来生成客户端代码
apache-cxf-3.0.1\bin wadl2java http://192.168.13.232:8084/ws_cxf/datatype?wsdl
生成客户端代码后即可编写客户端代码
package com.umgsai.datatype.client;
import java.util.List;
import java.util.Map;
import com.umgsai.datatype.DataTypeWS;//工具来生成客户端代码
import com.umgsai.datatype.DataTypeWSImplService;//工具来生成客户端代码
import com.umgsai.datatype.Student;//工具来生成客户端代码
public class ClientTest {
public static void main(String[] args) {
DataTypeWSImplService factory = new DataTypeWSImplService();
DataTypeWS dataTypeWSImplPort = factory.getDataTypeWSImplPort();
Map<Integer, Student> allStudentsMap = (Map<Integer, Student>) dataTypeWSImplPort.getAllStudentsMap();//Map暂时有问题。等换了JDK版本再做测试。
System.out.println(allStudentsMap);
Object studentById = dataTypeWSImplPort.getStudentById(1);
System.out.println(studentById);
List<Student> studentsByPrice = dataTypeWSImplPort.getStudentsByPrice(1000);
System.out.println(studentsByPrice);
}
}
本文出自 “优赛工作室” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/1563195