Webservice实践(六)CXF拦截器简介

本文介绍Cxf拦截器的工作原理及其实现方式。通过示例展示了如何在服务端配置入拦截器和出拦截器,并解释了拦截器链的运作过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

             拦截器是Cxf的基础,Cxf中很多的功能都是由内置的拦截器来实现的,拦截器在Cxf中由Interceptor表示。拦截器的作用类似axis2中handle。Cxf的拦截器包括入拦截器和出拦截器,所有的入拦截器或出拦截器构成了一个拦截器链,它们可以作用在Server端也可以作用在Client端。当需要使用拦截器链处理消息的时候,Cxf会确保对应的消息被拦截器链里面的每一个拦截器都执行一遍。拦截器链在Cxf中由InterceptorChain接口表示,org.apache.cxf.phase.PhaseInterceptorChain类的public synchronized boolean doIntercept(Message message)方法,它是拦截器链拦截Message的实现。当客户端发送一个请求到服务端时会经过客户端的出拦截器和服务端的入拦截器;当服务端对客户端的请求进行响应时对应的响应消息会经过服务端的出拦截器和客户端的入拦截器。

下面简单介绍一下服务端拦截器,在上一篇工程基础上进行如下修改:

在服务端应用里面,增加一个类,这个类继承自AbstractPhaseInterceptor。

package com.study.cxfws.msginterceptor;

import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;

public class WsInterceptor extends AbstractPhaseInterceptor<Message>{  
  
    public WsInterceptor(String phase) {  
        super(phase);  
    }  
  
    public void handleMessage(Message message) throws Fault {  
    	
        System.out.println("+++ into Interceptor+++");  
        System.out.println(message);  
        if(message.getDestination()!=null){  
            System.out.println(message.getId()+"#"+message.getDestination().getMessageObserver());            
        }  
        if(message.getExchange()!=null){  
            System.out.println(message.getExchange().getInMessage()+"#"+message.getExchange().getInFaultMessage());  
            System.out.println(message.getExchange().getOutMessage()+"#"+message.getExchange().getOutFaultMessage());  
        }  
        System.out.println("+++ Out Interceptor+++");  
    }  
  
}  
修改服务发布,注意下面标注红色的地方

package com.study.cxfws.impl;

import javax.jws.WebService;

import com.study.cxfws.StudentWs;
import com.study.cxfws.msginterceptor.WsInterceptor;
import com.study.dao.StudentDAO;
import com.study.dao.impl.StudentDAOImpl;

import org.apache.cxf.endpoint.Server;  
import org.apache.cxf.jaxws.JaxWsServerFactoryBean; 
import org.apache.cxf.phase.Phase;

@WebService  
public class StudentWsImpl implements  StudentWs {
	
	//Student的dao 类,负责处理student 实体类的操作
	private StudentDAO studentDAO;
	
	public  StudentWsImpl(){
		studentDAO = new StudentDAOImpl();
	}

	public boolean addStudent(String name, String sex, String birthday) {
		// 调用studentDAO.addStudent 方法入库
		System.out.println("Now put student into DB!");
		studentDAO.addStudent(name, sex, birthday);
		return true;

	}

	public String queryStudent(String studentName) {
		System.out.println("StudentWsImpl queryStudent->"+studentName);
		Object tmp = studentDAO.queryStudent(studentName);
		if (tmp== null) {
			return "null";
		} else {
			return tmp.toString();
		}

	}

	public static void main(String[] args) {


                System.out.println("web service start");
	        JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();  
	        //这里必须传入class,不能是接口,否则客户端会报异常 Could not instantiate service class ... because it is an interface
	        factory.setServiceClass(StudentWsImpl.class);  
	        factory.setAddress("http://localhost:8080/StudentWs");  
	          
	        factory.getInInterceptors().add(new WsInterceptor(Phase.RECEIVE));  
	        factory.getOutInterceptors().add(new WsInterceptor(Phase.SEND));  
	        Server server = factory.create();  
	        server.start();  
	        System.out.println("web service started");
	
	}


}

启动服务后,当客户端调用服务端接口的时候,我们可以看到拦截器发挥作用,日志如下:

web service start
二月 03, 2017 8:21:02 下午 org.apache.cxf.service.factory.ReflectionServiceFactoryBean buildServiceFromClass
INFO: Creating Service {http://impl.cxfws.study.com/}StudentWsImplService from class com.study.cxfws.StudentWs
二月 03, 2017 8:21:03 下午 org.apache.cxf.endpoint.ServerImpl initDestination
INFO: Setting the server's publish address to be http://localhost:8080/StudentWs
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
web service started
+++ into Interceptor+++
{org.apache.cxf.message.Message.PROTOCOL_HEADERS={Accept=[*/*], Cache-Control=[no-cache], connection=[keep-alive], Content-Length=[238], content-type=[text/xml; charset=UTF-8], Host=[localhost:8080], Pragma=[no-cache], SOAPAction=[""], User-Agent=[Apache CXF 2.7.6]}, HTTP_CONTEXT_MATCH_STRATEGY=stem, org.apache.cxf.request.url=http://localhost:8080/StudentWs, org.apache.cxf.request.uri=/StudentWs, HTTP.REQUEST=(POST /StudentWs)@1264815 org.eclipse.jetty.server.Request@134caf, HTTP.CONFIG=null, org.apache.cxf.transport.https.CertConstraints=null, Accept=*/*, org.apache.cxf.message.Message.PATH_INFO=/StudentWs, org.apache.cxf.message.Message.BASE_PATH=/StudentWs, org.apache.cxf.continuations.ContinuationProvider=org.apache.cxf.transport.http_jetty.continuations.JettyContinuationProvider@730f7532, org.apache.cxf.message.Message.IN_INTERCEPTORS=[org.apache.cxf.transport.https.CertConstraintsInterceptor@7bd760a1], org.apache.cxf.binding.soap.SoapVersion=org.apache.cxf.binding.soap.Soap11@7909298b, org.apache.cxf.message.Message.ENCODING=UTF-8, org.apache.cxf.message.Message.QUERY_STRING=null, HTTP.RESPONSE=HTTP/1.1 200 

, org.apache.cxf.security.SecurityContext=org.apache.cxf.transport.http.AbstractHTTPDestination$2@4886a2c1, org.apache.cxf.request.method=POST, org.apache.cxf.async.post.response.dispatch=true, org.apache.cxf.configuration.security.AuthorizationPolicy=null, org.apache.cxf.message.MessageFIXED_PARAMETER_ORDER=false, org.apache.cxf.transport.Destination=org.apache.cxf.transport.http_jetty.JettyHTTPDestination@7f275219, http.base.path=http://localhost:8080, Content-Type=text/xml; charset=UTF-8, HTTP.CONTEXT=ServletContext@o.e.j.s.h.ContextHandler{,null}}
null#org.apache.cxf.transport.ChainInitiationObserver@edebef9
{org.apache.cxf.message.Message.PROTOCOL_HEADERS={Accept=[*/*], Cache-Control=[no-cache], connection=[keep-alive], Content-Length=[238], content-type=[text/xml; charset=UTF-8], Host=[localhost:8080], Pragma=[no-cache], SOAPAction=[""], User-Agent=[Apache CXF 2.7.6]}, HTTP_CONTEXT_MATCH_STRATEGY=stem, org.apache.cxf.request.url=http://localhost:8080/StudentWs, org.apache.cxf.request.uri=/StudentWs, HTTP.REQUEST=(POST /StudentWs)@1264815 org.eclipse.jetty.server.Request@134caf, HTTP.CONFIG=null, org.apache.cxf.transport.https.CertConstraints=null, Accept=*/*, org.apache.cxf.message.Message.PATH_INFO=/StudentWs, org.apache.cxf.message.Message.BASE_PATH=/StudentWs, org.apache.cxf.continuations.ContinuationProvider=org.apache.cxf.transport.http_jetty.continuations.JettyContinuationProvider@730f7532, org.apache.cxf.message.Message.IN_INTERCEPTORS=[org.apache.cxf.transport.https.CertConstraintsInterceptor@7bd760a1], org.apache.cxf.binding.soap.SoapVersion=org.apache.cxf.binding.soap.Soap11@7909298b, org.apache.cxf.message.Message.ENCODING=UTF-8, org.apache.cxf.message.Message.QUERY_STRING=null, HTTP.RESPONSE=HTTP/1.1 200 

, org.apache.cxf.security.SecurityContext=org.apache.cxf.transport.http.AbstractHTTPDestination$2@4886a2c1, org.apache.cxf.request.method=POST, org.apache.cxf.async.post.response.dispatch=true, org.apache.cxf.configuration.security.AuthorizationPolicy=null, org.apache.cxf.message.MessageFIXED_PARAMETER_ORDER=false, org.apache.cxf.transport.Destination=org.apache.cxf.transport.http_jetty.JettyHTTPDestination@7f275219, http.base.path=http://localhost:8080, Content-Type=text/xml; charset=UTF-8, HTTP.CONTEXT=ServletContext@o.e.j.s.h.ContextHandler{,null}}#null
null#null
+++ Out Interceptor+++
Now put student into DB!
addStudent begin!
Name=Tom;Sex=male;Birthday=19780618
+++ into Interceptor+++
{javax.xml.ws.wsdl.port={http://impl.cxfws.study.com/}StudentWsImplPort, org.apache.cxf.ws.policy.EffectivePolicy=org.apache.cxf.ws.policy.EffectivePolicyImpl@6a4700ae, org.apache.cxf.service.model.MessageInfo=[MessageInfo OUTPUT: {http://cxfws.study.com/}addStudentResponse], http.headers.copied=true, wrote.envelope.start=true, org.apache.cxf.message.Message.PROTOCOL_HEADERS={}, javax.xml.ws.wsdl.service={http://impl.cxfws.study.com/}StudentWsImplService, org.apache.cxf.message.Message.ENCODING=UTF-8, org.apache.cxf.binding.soap.SoapVersion=org.apache.cxf.binding.soap.Soap11@7909298b, HTTP.RESPONSE=HTTP/1.1 200 
Content-Type: text/xml;charset=UTF-8

, javax.xml.ws.wsdl.interface={http://cxfws.study.com/}StudentWs, org.apache.cxf.mime.headers={}, javax.xml.ws.wsdl.operation={http://cxfws.study.com/}addStudent, javax.xml.ws.wsdl.description=http://localhost:8080/StudentWs?wsdl, org.apache.cxf.service.model.BindingMessageInfo=org.apache.cxf.service.model.BindingMessageInfo@5b7dd604, Content-Type=text/xml, org.apache.cxf.headers.Header.list=[]}
{javax.xml.ws.wsdl.port={http://impl.cxfws.study.com/}StudentWsImplPort, org.apache.cxf.service.model.MessageInfo=[MessageInfo INPUT: {http://cxfws.study.com/}addStudent], org.apache.cxf.message.Message.PROTOCOL_HEADERS={Accept=[*/*], Cache-Control=[no-cache], connection=[keep-alive], Content-Length=[238], content-type=[text/xml; charset=UTF-8], Host=[localhost:8080], Pragma=[no-cache], SOAPAction=[""], User-Agent=[Apache CXF 2.7.6]}, HTTP_CONTEXT_MATCH_STRATEGY=stem, org.apache.cxf.request.url=http://localhost:8080/StudentWs, javax.xml.ws.wsdl.interface={http://cxfws.study.com/}StudentWs, org.apache.cxf.request.uri=/StudentWs, HTTP.REQUEST=(POST /StudentWs)@1264815 org.eclipse.jetty.server.Request@134caf, HTTP.CONFIG=null, org.apache.cxf.transport.https.CertConstraints=null, Accept=*/*, org.apache.cxf.headers.Header.list=[], org.apache.cxf.message.Message.PATH_INFO=/StudentWs, org.apache.cxf.message.Message.BASE_PATH=/StudentWs, org.apache.cxf.continuations.ContinuationProvider=org.apache.cxf.transport.http_jetty.continuations.JettyContinuationProvider@730f7532, javax.xml.ws.wsdl.service={http://impl.cxfws.study.com/}StudentWsImplService, org.apache.cxf.message.Message.IN_INTERCEPTORS=[org.apache.cxf.transport.https.CertConstraintsInterceptor@7bd760a1], org.apache.cxf.binding.soap.SoapVersion=org.apache.cxf.binding.soap.Soap11@7909298b, org.apache.cxf.message.Message.ENCODING=UTF-8, org.apache.cxf.message.Message.QUERY_STRING=null, HTTP.RESPONSE=HTTP/1.1 200 
Content-Type: text/xml;charset=UTF-8

, org.apache.cxf.security.SecurityContext=org.apache.cxf.transport.http.AbstractHTTPDestination$2@4886a2c1, org.apache.cxf.request.method=POST, org.apache.cxf.async.post.response.dispatch=true, org.apache.cxf.configuration.security.AuthorizationPolicy=null, javax.xml.ws.wsdl.operation={http://cxfws.study.com/}addStudent, org.apache.cxf.message.MessageFIXED_PARAMETER_ORDER=false, org.apache.cxf.transport.Destination=org.apache.cxf.transport.http_jetty.JettyHTTPDestination@7f275219, org.apache.cxf.jaxws.context.WrappedMessageContext.SCOPES={}, javax.xml.ws.wsdl.description=http://localhost:8080/StudentWs?wsdl, http.base.path=http://localhost:8080, Content-Type=text/xml; charset=UTF-8, HTTP.CONTEXT=ServletContext@o.e.j.s.h.ContextHandler{,null}}#null
{javax.xml.ws.wsdl.port={http://impl.cxfws.study.com/}StudentWsImplPort, org.apache.cxf.ws.policy.EffectivePolicy=org.apache.cxf.ws.policy.EffectivePolicyImpl@6a4700ae, org.apache.cxf.service.model.MessageInfo=[MessageInfo OUTPUT: {http://cxfws.study.com/}addStudentResponse], http.headers.copied=true, wrote.envelope.start=true, org.apache.cxf.message.Message.PROTOCOL_HEADERS={}, javax.xml.ws.wsdl.service={http://impl.cxfws.study.com/}StudentWsImplService, org.apache.cxf.message.Message.ENCODING=UTF-8, org.apache.cxf.binding.soap.SoapVersion=org.apache.cxf.binding.soap.Soap11@7909298b, HTTP.RESPONSE=HTTP/1.1 200 
Content-Type: text/xml;charset=UTF-8

, javax.xml.ws.wsdl.interface={http://cxfws.study.com/}StudentWs, org.apache.cxf.mime.headers={}, javax.xml.ws.wsdl.operation={http://cxfws.study.com/}addStudent, javax.xml.ws.wsdl.description=http://localhost:8080/StudentWs?wsdl, org.apache.cxf.service.model.BindingMessageInfo=org.apache.cxf.service.model.BindingMessageInfo@5b7dd604, Content-Type=text/xml, org.apache.cxf.headers.Header.list=[]}#null
+++ Out Interceptor+++

关于拦截器参考了:

http://blog.youkuaiyun.com/wangnetkang/article/details/7799275

http://elim.iteye.com/blog/2248620


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值