前面讲了如何采用CXF开发webservice,现在来讲如何添加拦截器和自定义拦截器。
服务端代码:
HelloWorld implementor=new HelloWorldImpl();
String address="http://192.xxx.15.117:8089/helloWorld";
// Endpoint.publish(address, implementor); // jdk实现 暴露webservice接口
JaxWsServerFactoryBean factoryBean=new JaxWsServerFactoryBean();
factoryBean.setAddress(address); // 设置暴露地址
factoryBean.setServiceClass(HelloWorld.class); // 接口类
factoryBean.setServiceBean(implementor); // 设置实现类
factoryBean.getInInterceptors().add(new LoggingInInterceptor()); // 添加in拦截器 日志拦截器
factoryBean.getOutInterceptors().add(new LoggingOutInterceptor()); // 添加out拦截器 日志拦截器
factoryBean.getInInterceptors().add(new MyInterceptor()); //自定义拦截器
factoryBean.create(); // 创建webservice接口
自定义拦截器类:
public class MyInterceptor extends AbstractPhaseInterceptor<SoapMessage> { public MyInterceptor() {
super(Phase.PRE_INVOKE); // 在调用方法之前调用自定拦截器 } @SuppressWarnings("null")
public void handleMessage(SoapMessage message) throws Fault {
List<Header> headers=message.getHeaders();
if(headers==null && headers.size()==0){
throw new Fault(new IllegalArgumentException("没有Header,拦截器实施拦截"));
}
Header firstHeader=headers.get(0);
Element ele=(Element) firstHeader.getObject();
NodeList uList=ele.getElementsByTagName("userName");
NodeList pList=ele.getElementsByTagName("password");
if(uList.getLength()!=1){
throw new Fault(new IllegalArgumentException("用户名格式不对"));
}
if(pList.getLength()!=1){
throw new Fault(new IllegalArgumentException("密码格式不对"));
}
String userName=uList.item(0).getTextContent();
String password=pList.item(0).getTextContent(); if(!userName.equals("java1234")||!password.equals("123456")){
throw new Fault(new IllegalArgumentException("用户名或者密码错误!"));
}
} }
客户端代码:
先通过输入命令: wsdl2java http://192.xxx.15.117:8089/helloWorld?wsdl 生成需要的代码,谈话编写调用方法。
HelloWorldImplService service=new HelloWorldImplService();
HelloWorld helloWorld=service.getHelloWorldImplPort();
org.apache.cxf.endpoint.Client client=ClientProxy.getClient(helloWorld); client.getOutInterceptors().add(new AddHeaderInterceptor("java1234","123")); // 添加自定义拦截器
client.getInInterceptors().add(new LoggingInInterceptor()); // 添加In拦截器 日志拦截器
client.getOutInterceptors().add(new LoggingOutInterceptor()); // 添加Out拦截器 日志拦截器
自定义拦截器:
public class AddHeaderInterceptor extends AbstractPhaseInterceptor<SoapMessage> { private String userName;
private String password; public AddHeaderInterceptor(String userName,String password) {
super(Phase.PREPARE_SEND); // 准备发送SOAP消息的时候调用拦截器
this.userName=userName;
this.password=password;
} public void handleMessage(SoapMessage message) throws Fault {
List<Header> headerList=message.getHeaders(); Document doc=DOMUtils.createDocument();
Element ele=doc.createElement("authHeader");
Element uElement=doc.createElement("userName");
uElement.setTextContent(userName);
Element pElement=doc.createElement("password");
pElement.setTextContent(password); ele.appendChild(uElement);
ele.appendChild(pElement); headerList.add(new Header(new QName("java1234"),ele)); } }
完成!