首页 > 网站 > WEB开发 > 正文

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

2024-04-27 15:03:58
字体:
来源:转载
供稿:网友

             拦截器是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 buildServiceFromClassINFO: Creating Service {http://impl.cxfws.study.com/}StudentWsImplService from class com.study.cxfws.StudentWs二月 03, 2017 8:21:03 下午 org.apache.cxf.endpoint.ServerImpl initDestinationINFO: Setting the server's publish address to be http://localhost:8080/StudentWsSLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".SLF4J: Defaulting to no-Operation (NOP) logger implementationSLF4J: 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}}#nullnull#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.csdn.net/wangnetkang/article/details/7799275

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


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表