本文主要对比一下spring mvc中可使用的几类拦截器。html
主要分Filter及interceptor。java
是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
在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
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
类型 | 范围 | 执行链处理 | 异常 | 经典实用 |
---|---|---|---|---|
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也能够。