apache cxf框架最主要的扩展点就是拦截器了,拦截器可以在不对核心模块进行修改的情况下,动态添加很多功能。拦截器和JAX-WS Handler、Filter的功能类似,当服务被调用时,就会创建一个拦截器链(Interceptor Chain),拦截器链在服务输入(IN)或输出(OUT)阶段实现附加功能。
在实际的webservice开发中会有类似需求:对客户端传过来的参数进行校验,如果参数不符合规则,就中断返回,使之不进入实际业务逻辑的执行,并给客户端返回自定义的信息。实现上述需求的代码如下:
public class ValidateInterceptor extends AbstractPhaseInterceptor<XMLMessage>{
private Logger log = LoggerFactory.getLogger(getClass());
public ValidateInterceptor(String phase) {
super(phase);
}
public ValidateInterceptor() {
super(Phase.PRE_INVOKE);
}
@Override
public void handleMessage(XMLMessage arg0) throws Fault {
MessageContentsList lstContent = MessageContentsList.getContentsList(arg0);
try {
MsgObject msgObject = (MsgObject)ValidateUtil.valitWlefParams(lstContent.get(0));
if("error".equals(msgObject.getReturnCode())) {
HttpServletResponse response = (HttpServletResponse)arg0.get(AbstractHTTPDestination.HTTP_RESPONSE);
ServletOutputStream out = response.getOutputStream();
String outMsg = JsonUtil.toJson(msgObject);
log.info("回送字符串:" + outMsg);
try {
out.write(outMsg.getBytes("utf-8"));
out.flush();
arg0.getInterceptorChain().doInterceptStartingAfter(arg0, "org.apache.cxf.jaxrs.interceptor.JAXRSOutInterceptor");
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}