引言
CXF拦截器是Apache CXF里面一个很重要的功能,它能够动态操作响应数据和请求数据,降低代码的耦合性,提供代码的内聚性。这对于CXF这个以处理消息为中心的服务框架来说是非常有用的,CXF通过在Interceptor中对消息进行特殊处理,实现了很多重要功能模块,例如:日志记录,Soap消息处理,消息的压缩处理。
一、拦截器分类
1.按所处的位置分:服务器端拦截器、客户端拦截器
2.按消息的方向分:入拦截器、出拦截器
3.按定义者分:系统拦截器,自定义拦截器
二、拦截器API
在最顶层有个拦截器接口 Interceptor接口
AbstractPhaseInterceptor(自定义拦截器继承这个接口)
LoggingInterceptor(系统日志入拦截器类)
LoggingOutInterceptor(系统日志出拦截器类)
三、添加日志入拦截器
继续用上篇的CXF WebService代码,再添加一个日志入拦截器。
package com.gpj.service.endpoint; import java.util.List; import javax.xml.ws.Endpoint; import org.apache.cxf.interceptor.Interceptor; import org.apache.cxf.interceptor.LoggingInInterceptor; import org.apache.cxf.jaxws22.EndpointImpl; import org.apache.cxf.message.Message; import com.gpj.service.HelloServiceImpl; public class ServiceTest { public static void main(String[] args) { String address="http://localhost:8888/service/HelloService"; Endpoint publish = Endpoint.publish(address, new HelloServiceImpl()); EndpointImpl endpointImpl = (EndpointImpl) publish; //服务端的日志入拦截器 List<Interceptor<? extends Message>> inFaultInterceptors = endpointImpl.getInFaultInterceptors(); inFaultInterceptors.add(new LoggingInInterceptor()); //服务器端日志出拦截器 List<Interceptor<? extends Message>> outInterceptors = endpointImpl.getOutInterceptors(); outInterceptors.add(new LoggingInInterceptor()); System.out.println("JDKservice发布成功"); } }
再次运行main方法。打开eclipse的Web Service Explorer,访问http://localhost:8080/service/HelloService?wsdl