拦截器和过滤器区别

Posted 王小森

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了拦截器和过滤器区别相关的知识,希望对你有一定的参考价值。

因为过滤器Filter是servlet相关的由serviette容器tomcat管理,而拦截器Interceptor是spring管理,因为web程序执行过程就是先启动tomcat容器,之后再在容器中调用spring那些东西,所以首先我猜测顺序是先走Filter过滤器 后进Interceptor拦截器

我通过程序进行测试来看区别,不说了,先上代码:

拦截器代码:

 

/**
 * 拦截器校验参数
 * Created by wanghongsen on 16-3-31.
 */
public class ControllerInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(ControllerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        logger.info("###################### before interceptor  #######################");

        if (UntilService.checkParameter(httpServletRequest)) {
            logger.info("ControllerInterceptor-preHandle-parameter is regular");
            return true;
        } else {
            logger.info("ControllerInterceptor-preHandle-parameter is empty");
            httpServletResponse.sendRedirect("/flight.jsp");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        logger.info("%%%%%%%%%%%%%%%%%%%%%%  after interceptor  %%%%%%%%%%%%%%%%%%%%%%%");

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        logger.info("%%%%%%%%%%%%%%%%%%%%%%  complete interceptor  %%%%%%%%%%%%%%%%%%%%%%%");

    }
}

 

过滤器代码:

 

/**
 * 过滤器
 * Created by wanghongsen on 16-3-31.
 */

public class TicketFilter implements Filter {
    private Logger logger = LoggerFactory.getLogger(TicketFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        logger.info("###################   before do filter    ######################");
        filterChain.doFilter(servletRequest, servletResponse);
        logger.info("%%%%%%%%%%%%%%%%%%%   after do filter    %%%%%%%%%%%%%%%%%%%%%");
    }

    @Override
    public void destroy() {

    }
}


执行完之查看日志输出如下:

 

 

14:46:48.558 [http-bio-8080-exec-10] INFO  c.q.fresh.base.filter.TicketFilter - ###################   before do filter    ######################
14:46:48.558 [http-bio-8080-exec-10] DEBUG o.s.web.servlet.DispatcherServlet - DispatcherServlet with name ‘springMVCDispatcher‘ processing GET request for [/ticket/save]
14:46:48.558 [http-bio-8080-exec-10] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Looking up handler method for path /ticket/save
14:46:48.559 [http-bio-8080-exec-10] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Returning handler method [public java.lang.String com.qunar.fresh.ticket.controller.TicketController.save(javax.servlet.http.HttpServletRequest)]
14:46:48.559 [http-bio-8080-exec-10] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean ‘ticketController‘
14:46:48.559 [http-bio-8080-exec-10] DEBUG o.s.web.servlet.DispatcherServlet - Last-Modified value for [/ticket/save] is: -1
14:46:48.559 [http-bio-8080-exec-10] INFO  c.q.f.b.i.ControllerInterceptor - ###################### before interceptor  #######################
14:46:48.559 [http-bio-8080-exec-10] INFO  c.q.f.b.i.ControllerInterceptor - ControllerInterceptor-preHandle-parameter is regular
14:46:48.576 [http-bio-8080-exec-10] DEBUG org.mybatis.spring.SqlSessionUtils - Creating a new SqlSession
14:46:48.580 [http-bio-8080-exec-10] DEBUG org.mybatis.spring.SqlSessionUtils - SqlSession [[email protected]] was not registered for synchronization because synchronization is not active
14:46:48.587 [http-bio-8080-exec-10] DEBUG o.s.jdbc.datasource.DataSourceUtils - Fetching JDBC Connection from DataSource
14:46:48.594 [http-bio-8080-exec-10] DEBUG o.m.s.t.SpringManagedTransaction - JDBC Connection [[email protected]] will not be managed by Spring
14:46:48.595 [http-bio-8080-exec-10] DEBUG c.q.f.ticket.dao.TicketDao.insert - ooo Using Connection [[email protected]]
14:46:48.603 [http-bio-8080-exec-10] DEBUG c.q.f.ticket.dao.TicketDao.insert - ==>  Preparing: INSERT INTO ticket_info( airline, flight_no, passenger_name, passenger_age, flight_date ) VALUES ( ?, ?, ?, ?, ? )
14:46:48.703 [http-bio-8080-exec-10] DEBUG c.q.f.ticket.dao.TicketDao.insert - ==> Parameters: 海南航空(String), 42s(String), 王红森(String), 333(Integer), 2016-03-01 19:48:19.0(Timestamp)
14:46:48.707 [http-bio-8080-exec-10] DEBUG c.q.f.ticket.dao.TicketDao.insert - <==    Updates: 1
14:46:48.712 [http-bio-8080-exec-10] DEBUG c.a.druid.pool.PreparedStatementPool - {conn-10003, pstmt-20000} enter cache
14:46:48.713 [http-bio-8080-exec-10] DEBUG org.mybatis.spring.SqlSessionUtils - Closing non transactional SqlSession [[email protected]]
14:46:48.713 [http-bio-8080-exec-10] DEBUG o.s.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource
14:46:48.713 [http-bio-8080-exec-10] INFO  c.q.f.t.controller.TicketController - TicketController-save-order success!
14:46:48.715 [http-bio-8080-exec-10] INFO  c.q.f.b.i.ControllerInterceptor - %%%%%%%%%%%%%%%%%%%%%%  after interceptor  %%%%%%%%%%%%%%%%%%%%%%%
14:46:48.715 [http-bio-8080-exec-10] DEBUG o.s.w.s.view.BeanNameViewResolver - No matching bean found for view name ‘ticket/success‘
14:46:48.717 [http-bio-8080-exec-10] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Invoking afterPropertiesSet() on bean with name ‘ticket/success‘
14:46:48.717 [http-bio-8080-exec-10] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean ‘org.springframework.transaction.config.internalTransactionAdvisor‘
14:46:48.717 [http-bio-8080-exec-10] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean ‘org.springframework.transaction.config.internalTransactionAdvisor‘
14:46:48.718 [http-bio-8080-exec-10] DEBUG o.s.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.InternalResourceView: name ‘ticket/success‘; URL [/WEB-INF/views/ticket/success.jsp]] in DispatcherServlet with name ‘springMVCDispatcher‘
14:46:48.719 [http-bio-8080-exec-10] DEBUG o.s.w.s.view.InternalResourceView - Forwarding to resource [/WEB-INF/views/ticket/success.jsp] in InternalResourceView ‘ticket/success‘
14:46:48.754 [http-bio-8080-exec-10] INFO  c.q.f.b.i.ControllerInterceptor - %%%%%%%%%%%%%%%%%%%%%%  complete interceptor  %%%%%%%%%%%%%%%%%%%%%%%
14:46:48.754 [http-bio-8080-exec-10] DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request
14:46:48.754 [http-bio-8080-exec-10] INFO  c.q.fresh.base.filter.TicketFilter - %%%%%%%%%%%%%%%%%%%   after do filter    %%%%%%%%%%%%%%%%%%%%%

 

经过对日志分析,总结出拦截器和过滤器在执行结果上的先后顺序是

Filterpre->service->dispatcher->preHandle->controller->postHandle->afterCompletion->FilterAfter

流程图如下:

技术分享图片

 

过滤器和拦截器的区别:

1 拦截器是基于java的反射机制的,而过滤器是基于函数回调。
2 拦截器不依赖与servlet容器,过滤器依赖与servlet容器。
3 拦截器只能对action请求起作用,而过滤器则可以对几乎所有的请求起作用。
4 拦截器可以访问action上下文、值栈里的对象,而过滤器不能访问。
5 在action的生命周期中,拦截器可以多次被调用,而过滤器只能在容器初始化时被调用一次。

6 拦截器可以获取IOC容器中的各个bean,而过滤器就不行,这点很重要,在拦截器里注入一个service,可以调用业务逻辑。

 






以上是关于拦截器和过滤器区别的主要内容,如果未能解决你的问题,请参考以下文章

SpringMVC -- 拦截器(作用与过滤器的区别示例拦截器实现登录拦截核心代码)

java web 过滤器跟拦截器的区别和使用

java web 过滤器跟拦截器的区别和使用

SpringMVC的拦截器和过滤器的区别与联系

拦截器(Interceptor)和过滤器(Filter)的区别和执行顺序)

java web 过滤器跟拦截器的区别和使用