序
本文主要對比一下spring mvc中可以使用的幾類攔截器。
分類
主要分Filter及interceptor。
Filter
是servlet規(guī)范中的Filter,spring中有一個基本的實現(xiàn)叫做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();
}
}
//......
這個類主要實現(xiàn)了spring生命周期的幾個接口,方便作為bean納入IOC容器管理。
如果是在web.xml定義的話,支持將參數(shù)映射到bean中的屬性
OncePerRequestFilter
在spring中,filter都默認繼承OncePerRequestFilter,他確保一次請求只通過一次filter,而不重復(fù)執(zhí)行。
此方式是為了兼容不同的web container,特意而為之(JSR168),也就是說并不是所有的container都像我們期望的只過濾一次,servlet版本不同.為了兼容各種不同的運行環(huán)境和版本,默認filter繼承OncePerRequestFilter是一個比較穩(wěn)妥的選擇。
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來標(biāo)識filter是否已經(jīng)執(zhí)行過。
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來執(zhí)行
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,afterCompletion
- preHandle
這個里頭返回false,則會停止繼續(xù)往下執(zhí)行 - postHandle
后處理回調(diào)方法,實現(xiàn)處理器的后處理,但在渲染視圖之前執(zhí)行,可以在這里額外往視圖添加額外的變量等(在preHandle成功執(zhí)行完,返回true的情況下執(zhí)行) - afterCompletion
在preHandle成功執(zhí)行完,返回true的情況下執(zhí)行.整個請求處理完畢回調(diào)方法,即在視圖渲染完畢時回調(diào)
對比
類型 | 范圍 | 執(zhí)行鏈處理 | 異常 | 經(jīng)典實用 |
---|---|---|---|---|
filter | filter是servlet是定義,在支持servlet的容器中都可以支持 | doFilter方法沒有返回值,每個filter里頭去控制是否往下執(zhí)行,不想往下執(zhí)行的話,可以自己設(shè)定response body和status然后提前返回 | 異常無法被spring的ExceptionHandler捕獲,直接500 | CharacterEncodingFilter CorsFilter CsrfFilter MetricsFilter MultipartFilter OpenEntityManagerInViewFilter WebRequestTraceFilter |
HandlerInterceptor | 在spring mvc中支持 | preHandle方法返回布爾值,當(dāng)布爾值為true的時候繼續(xù)往下一個interceptor執(zhí)行,返回false則立即返回,可以自己設(shè)定response body和status,也可以拋異常,spring會統(tǒng)一攔截處理 | 異常可以被ExceptionHandler捕獲 | MvcEndpointSecurityInterceptor UserRoleAuthorizationInterceptor |
記錄耗時等用filter的比較多,比較全面;執(zhí)行鑒權(quán)相關(guān)的用HandlerInterceptor的比較多,當(dāng)然用filter也可以。