服务端:
第一步、定义接口
@WebService @SOAPBinding(style = SOAPBinding.Style.RPC) public interface IUser { @WebMethod void addUser(UserDto userDto); }
第二步、接口实现
public class UserImpl implements IUser {
@Override
public void addUser(UserDto userDto) {
System.out.println("正在新增信息");
System.out.println(new Gson().toJson(userDto));
}
}
第三步、定义DTO
@XmlRootElement(name = "UserDto")
@XmlAccessorType(XmlAccessType.FIELD)
//@XmlType(namespace = "dto.inter.server.cxf.com") 定义DTO的nameSace,发布后的nameSpace和service一致 可以在此处更改
public class UserDto implements Serializable {
private static final long serialVersionUID = -5691763516137528419L;
private String id;
private String name;
private int age;
private String mobile;
private String addr;
……}
第四步、服务发布
//使用JaxWsServerFactoryBean发布服务,需要在类上加入@WebService注解,
//如果不加,当前类中的方法都不能被发布为web方法
JaxWsServerFactoryBean bean = new JaxWsServerFactoryBean();
//发布服务的地址
bean.setAddress("http://10.26.160.165:8080/user");
//接口类型
bean.setServiceClass(IUser.class);
//接口的实现类
bean.setServiceBean(new UserImpl());
//发布服务
bean.create();
客户端
public static void main(String[] args) throws Exception {
Client userClient = getCxfClient("http://localhost:8080/user/UserService?wsdl");
Object dataTypes = Thread.currentThread().getContextClassLoader().loadClass("com.cxf.server.inter.UserDto").newInstance();
Method id = dataTypes.getClass().getMethod("setId", String.class);
Method name = dataTypes.getClass().getMethod("setName", String.class);
Method age = dataTypes.getClass().getMethod("setAge", int.class);
Method mobile = dataTypes.getClass().getMethod("setMobile", String.class);
Method addr = dataTypes.getClass().getMethod("setAddr", String.class);
id.invoke(dataTypes, "0001");
name.invoke(dataTypes, "UUU");
age.invoke(dataTypes, 18);
mobile.invoke(dataTypes, "110");
addr.invoke(dataTypes, "杭州");
Object result = userClient.invoke("addUser",dataTypes);
System.out.println("喻攀大搓逼");
}
public static Client getCxfClient(String wsdlUrl) {
JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();
Client client = factory.createClient(wsdlUrl);
HTTPConduit conduit = (HTTPConduit) client.getConduit();
HTTPClientPolicy policy = new HTTPClientPolicy();
String connectionTimeout = "2000";
if (connectionTimeout != null && !"".equals(connectionTimeout)) {
int conTimeout = Integer.parseInt(connectionTimeout);
policy.setConnectionTimeout(conTimeout); //连接超时时间
}
//policy.setReceiveTimeout(120000);//请求超时时间.
conduit.setClient(policy);
return client;
}