前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >spring mvc中的几类拦截器对比

spring mvc中的几类拦截器对比

作者头像
code4it
发布2018-09-17 14:58:37
1.5K0
发布2018-09-17 14:58:37
举报
文章被收录于专栏:码匠的流水账码匠的流水账

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

分类

主要分Filter及interceptor。

Filter

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

代码语言:javascript
复制
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是一个比较稳妥的选择。

代码语言:javascript
复制
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 {

代码语言:javascript
复制
/**
 * Intercept the execution of a handler. Called after HandlerMapping determined
 * an appropriate handler object, but before HandlerAdapter invokes the handler.
 * <p>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.
 * <p><strong>Note:</strong> 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.
 * <p>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.
 * <p><strong>Note:</strong> 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.
 * <p>Note: Will only be called if this interceptor's {@code preHandle}
 * method has successfully completed and returned {@code true}!
 * <p>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.
 * <p><strong>Note:</strong> 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

  • Filters and Spring
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2017-09-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 码匠的流水账 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 分类
  • Filter
    • OncePerRequestFilter
    • HandlerInterceptor
    • 对比
    • doc
    相关产品与服务
    容器服务
    腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档