spring mvc中的幾類攔截器對比

本文主要對比一下spring mvc中可使用的幾類攔截器。html

分類

主要分Filter及interceptor。java

Filter

是servlet規範中的Filter,spring中有一個基本的實現叫作org/springframework/web/filter/GenericFilterBean.javaweb

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中的屬性spring

OncePerRequestFilter

在spring中,filter都默認繼承OncePerRequestFilter,他確保一次請求只經過一次filter,而不重複執行。mvc

此方式是爲了兼容不一樣的web container,特地而爲之(JSR168),也就是說並非全部的container都像咱們指望的只過濾一次,servlet版本不一樣.爲了兼容各類不一樣的運行環境和版本,默認filter繼承OncePerRequestFilter是一個比較穩妥的選擇。app

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是否已經執行過。async

HandlerInterceptor

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

基於execution chains來執行post

public interface HandlerInterceptor {

    /**
     * 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,afterCompletionthis

  • 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

相關文章
相關標籤/搜索