博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring mvc中的几类拦截器对比
阅读量:7114 次
发布时间:2019-06-28

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

本文主要对比一下spring mvc中可以使用的几类拦截器。

分类

主要分Filter及interceptor。

Filter

是servlet规范中的Filter,spring中有一个基本的实现叫做org/springframework/web/filter/GenericFilterBean.java

public abstract class GenericFilterBean implements        Filter, BeanNameAware, EnvironmentAware, ServletContextAware, InitializingBean, DisposableBean {    @Override    public final void setBeanName(String beanName) {        this.beanName = beanName;    }    @Override    public void setEnvironment(Environment environment) {        this.environment = environment;    }    @Override    public final void setServletContext(ServletContext servletContext) {        this.servletContext = servletContext;    }    @Override    public void afterPropertiesSet() throws ServletException {        initFilterBean();    }}//......

这个类主要实现了spring生命周期的几个接口,方便作为bean纳入IOC容器管理。

如果是在web.xml定义的话,支持将参数映射到bean中的属性

OncePerRequestFilter

在spring中,filter都默认继承OncePerRequestFilter,他确保一次请求只通过一次filter,而不重复执行。

此方式是为了兼容不同的web container,特意而为之(JSR168),也就是说并不是所有的container都像我们期望的只过滤一次,servlet版本不同.为了兼容各种不同的运行环境和版本,默认filter继承OncePerRequestFilter是一个比较稳妥的选择。

public abstract class OncePerRequestFilter extends GenericFilterBean {public static final String ALREADY_FILTERED_SUFFIX = ".FILTERED";protected String getAlreadyFilteredAttributeName() {        String name = getFilterName();        if (name == null) {            name = getClass().getName();        }        return name + ALREADY_FILTERED_SUFFIX;    }  //......}

通过filtername+ALREADY_FILTERED_SUFFIX来标识filter是否已经执行过。

HandlerInterceptor

org/springframework/spring-webmvc/4.3.9.RELEASE/spring-webmvc-4.3.9.RELEASE-sources.jar!/org/springframework/web/servlet/HandlerInterceptor.java

基于execution chains来执行

public interface HandlerInterceptor {    /**     * Intercept the execution of a handler. Called after HandlerMapping determined     * an appropriate handler object, but before HandlerAdapter invokes the handler.     * 

DispatcherServlet processes a handler in an execution chain, consisting * of any number of interceptors, with the handler itself at the end. * With this method, each interceptor can decide to abort the execution chain, * typically sending a HTTP error or writing a custom response. *

Note: special considerations apply for asynchronous * request processing. For more details see * {@link org.springframework.web.servlet.AsyncHandlerInterceptor}. * @param request current HTTP request * @param response current HTTP response * @param handler chosen handler to execute, for type and/or instance evaluation * @return {@code true} if the execution chain should proceed with the * next interceptor or the handler itself. Else, DispatcherServlet assumes * that this interceptor has already dealt with the response itself. * @throws Exception in case of errors */ boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception; /** * Intercept the execution of a handler. Called after HandlerAdapter actually * invoked the handler, but before the DispatcherServlet renders the view. * Can expose additional model objects to the view via the given ModelAndView. *

DispatcherServlet processes a handler in an execution chain, consisting * of any number of interceptors, with the handler itself at the end. * With this method, each interceptor can post-process an execution, * getting applied in inverse order of the execution chain. *

Note: special considerations apply for asynchronous * request processing. For more details see * {@link org.springframework.web.servlet.AsyncHandlerInterceptor}. * @param request current HTTP request * @param response current HTTP response * @param handler handler (or {@link HandlerMethod}) that started asynchronous * execution, for type and/or instance examination * @param modelAndView the {@code ModelAndView} that the handler returned * (can also be {@code null}) * @throws Exception in case of errors */ void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception; /** * Callback after completion of request processing, that is, after rendering * the view. Will be called on any outcome of handler execution, thus allows * for proper resource cleanup. *

Note: Will only be called if this interceptor's {@code preHandle} * method has successfully completed and returned {@code true}! *

As with the {@code postHandle} method, the method will be invoked on each * interceptor in the chain in reverse order, so the first interceptor will be * the last to be invoked. *

Note: special considerations apply for asynchronous * request processing. For more details see * {@link org.springframework.web.servlet.AsyncHandlerInterceptor}. * @param request current HTTP request * @param response current HTTP response * @param handler handler (or {@link HandlerMethod}) that started asynchronous * execution, for type and/or instance examination * @param ex exception thrown on handler execution, if any * @throws Exception in case of errors */ void afterCompletion( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception;}

主要定义了三个方法,preHandle,postHandle,afterCompletion

  • preHandle
    这个里头返回false,则会停止继续往下执行
  • postHandle
    后处理回调方法,实现处理器的后处理,但在渲染视图之前执行,可以在这里额外往视图添加额外的变量等(在preHandle成功执行完,返回true的情况下执行)
  • afterCompletion
    在preHandle成功执行完,返回true的情况下执行.整个请求处理完毕回调方法,即在视图渲染完毕时回调

对比

类型 范围 执行链处理 异常 经典实用
filter filter是servlet是定义,在支持servlet的容器中都可以支持 doFilter方法没有返回值,每个filter里头去控制是否往下执行,不想往下执行的话,可以自己设定response body和status然后提前返回 异常无法被spring的ExceptionHandler捕获,直接500 CharacterEncodingFilter
CorsFilter
CsrfFilter
MetricsFilter
MultipartFilter
OpenEntityManagerInViewFilter
WebRequestTraceFilter
HandlerInterceptor 在spring mvc中支持 preHandle方法返回布尔值,当布尔值为true的时候继续往下一个interceptor执行,返回false则立即返回,可以自己设定response body和status,也可以抛异常,spring会统一拦截处理 异常可以被ExceptionHandler捕获 MvcEndpointSecurityInterceptor
UserRoleAuthorizationInterceptor

记录耗时等用filter的比较多,比较全面;执行鉴权相关的用HandlerInterceptor的比较多,当然用filter也可以。

doc

转载地址:http://jjwel.baihongyu.com/

你可能感兴趣的文章
github 上有趣又实用的前端项目(持续更新,欢迎补充)
查看>>
【Under-the-hood-ReactJS-Part6】React源码解读
查看>>
matlab绘制peano(皮亚诺)曲线和koch(科赫曲线,雪花曲线)分形曲线
查看>>
Mybatis之设计模式之迭代器模式
查看>>
小程序TAB列表切换内容动态变化,scrollview高度根据内容动态获取
查看>>
swoole_table 实现原理剖析
查看>>
你需要知道面试中的10个JavaScript概念
查看>>
Java源码阅读之HashMap - JDK1.8
查看>>
Dell服务器系统安装后无法正常进入系统
查看>>
Silverlight/Windows8/WPF/WP7/HTML5周学习导读(9月17日-9月23日)
查看>>
Tap-Ahead:让移动搜索更加便捷的解决之道
查看>>
华为vlan划分,单臂路由以及静态路由
查看>>
3.VMware vsphere 5.0新体验-安装VMware Center
查看>>
趣题: 一道面试题的解法
查看>>
Android应用程序启动过程源代码分析(5)
查看>>
查询整个数据库中某个特定值所在的表和字段的方法
查看>>
在存储过程中编写正确的事务处理代码(SQL Server 2000 & 2005)
查看>>
数据库邮件
查看>>
adstrtal.sh报超时错误 ERROR : Timed out( 100000 ): Interrupted Exception
查看>>
一个前端工程师的基本修养
查看>>