博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
拦截器和过滤器区别
阅读量:5331 次
发布时间:2019-06-14

本文共 7406 字,大约阅读时间需要 24 分钟。

因为过滤器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/save14: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 [org.apache.ibatis.session.defaults.DefaultSqlSession@4f06dee3] 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 [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@664a7d46] 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 [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@664a7d46] 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 [org.apache.ibatis.session.defaults.DefaultSqlSession@4f06dee3] 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,可以调用业务逻辑。

 

转载于:https://www.cnblogs.com/wanghongsen/p/8082566.html

你可能感兴趣的文章
创新课程管理系统数据库设计心得
查看>>
管道,数据共享,进程池
查看>>
SDUTOJ3754_黑白棋(纯模拟)
查看>>
把word文档中的所有图片导出
查看>>
ubuntu 18.04取消自动锁屏以及设置键盘快捷锁屏
查看>>
arcgis api 4.x for js 结合 Echarts4 实现散点图效果(附源码下载)
查看>>
YTU 2625: B 构造函数和析构函数
查看>>
apache自带压力测试工具ab的使用及解析
查看>>
加固linux
查看>>
Hyper-V虚拟机上安装一个图形界面的Linux系统
查看>>
字符串类型的相互转换
查看>>
基础学习:C#中float的取值范围和精度
查看>>
web前端面试题2017
查看>>
【Crash Course Psychology】2. Research & Experimentation笔记
查看>>
关于 linux 的 limit 的设置
查看>>
MTK笔记
查看>>
ERROR: duplicate key value violates unique constraint "xxx"
查看>>
激活office 365 的启动文件
查看>>
无法根据中文查找
查看>>
[简讯]phpMyAdmin项目已迁移至GitHub
查看>>