SpringWeb 攔截器

前言

spring攔截器能幫我們實現驗證是否登陸、驗簽校驗請求是否合法、預先設置數據等功能,那麼該如何設置攔截器以及它的原理如何呢,下面將進行簡單的介紹

1.設置

HandlerInterceptor接口
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}.
	 * <p>The default implementation returns {@code true}.
	 * @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
	 */
	default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		return true;
	}

	/**
	 * 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}.
	 * <p>The default implementation is empty.
	 * @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
	 */
	default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable 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}.
	 * <p>The default implementation is empty.
	 * @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
	 */
	default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable Exception ex) throws Exception {
	}

}

自定義攔截器需要實現HandlerInteceptor接口,該接口有三個方法:

preHandle:主要在映射適配器執行handler之前調用,若返回為true則繼續往下執行handler,若返回為false則直接返回不繼續處理請求

postHandle:主要在適配器執行handler之後調用 

afterCompletion:在postHandle後調用可清理一些數據,若preHandle返回false那麼會調用完此方法後再返回

@Component
public class CustomInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    System.out.println("-------------攔截請求:" + request.getRequestURI() + "-------------");
    // 可以根據request設置請求頭、或從請求頭提取信息等等...
    return true;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
      @Nullable ModelAndView modelAndView) throws Exception {
    System.out.println("postHandle ....");
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
      @Nullable Exception ex) throws Exception {
    System.out.println("afterCompletion ....");
  }
}

接着創建配置類,實現WebMvcConfigurer接口,重寫addInterceptors方法將自定義攔截器添加,並且加上@EnableWebMvc註解 (springboot項目會自動配置)

@Configuration
@EnableWebMvc
public class MyMvcConfigurer implements WebMvcConfigurer {

  @Resource
  private CustomInterceptor customInterceptor;

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(customInterceptor)
        .addPathPatterns("/**");
  }
}

配置完之後啟動項目訪問某個url路徑,從控制台可以看到攔截器確實生效了

 

2.原理

首先是@EnableWebMvc註解,spring會解析並導入DelegatingWebMvcConfiguration這個bean,繼承關係如下,主要邏輯都寫在父類WebMvcConfigurationSupport中

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}

WebMvcConfigurationSupport中會創建一個映射處理器RequestMappingHandlerMapping

@Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping() {
	RequestMappingHandlerMapping mapping = createRequestMappingHandlerMapping();
	mapping.setOrder(0);
	// 設置攔截器到mapping
	mapping.setInterceptors(getInterceptors());
	// 設置內容協商管理器
	mapping.setContentNegotiationManager(mvcContentNegotiationManager());
	// 跨域配置
	mapping.setCorsConfigurations(getCorsConfigurations());

	// 路徑匹配設置
	PathMatchConfigurer configurer = getPathMatchConfigurer();

	Boolean useSuffixPatternMatch = configurer.isUseSuffixPatternMatch();
	if (useSuffixPatternMatch != null) {
		mapping.setUseSuffixPatternMatch(useSuffixPatternMatch);
	}
	Boolean useRegisteredSuffixPatternMatch = configurer.isUseRegisteredSuffixPatternMatch();
	if (useRegisteredSuffixPatternMatch != null) {
		mapping.setUseRegisteredSuffixPatternMatch(useRegisteredSuffixPatternMatch);
	}
	Boolean useTrailingSlashMatch = configurer.isUseTrailingSlashMatch();
	if (useTrailingSlashMatch != null) {
		mapping.setUseTrailingSlashMatch(useTrailingSlashMatch);
	}

	UrlPathHelper pathHelper = configurer.getUrlPathHelper();
	if (pathHelper != null) {
		mapping.setUrlPathHelper(pathHelper);
	}
	PathMatcher pathMatcher = configurer.getPathMatcher();
	if (pathMatcher != null) {
		mapping.setPathMatcher(pathMatcher);
	}

	return mapping;
}


#獲取攔截器
protected final Object[] getInterceptors() {
	if (this.interceptors == null) {
		InterceptorRegistry registry = new InterceptorRegistry();
		// 調用DelegatingWebMvcConfiguration.addInterceptors 添加自定義的攔截器
		addInterceptors(registry);
		registry.addInterceptor(new ConversionServiceExposingInterceptor(mvcConversionService()));
		registry.addInterceptor(new ResourceUrlProviderExposingInterceptor(mvcResourceUrlProvider()));
		// 獲取攔截器並根據order排序,若有匹配路徑則封裝成MappedInterceptor
		this.interceptors = registry.getInterceptors();
	}
	return this.interceptors.toArray();
}

注意這一行代碼mapping.setInterceptors(getInterceptors());  getInterceptors方法會調用子類DelegatingWebMvcConfiguration的addInterceptors方法,接着會調用委託類即我們自定義配置類MyMvcConfigurer類的addInterceptors方法,將自定義的攔截器添加到攔截器註冊類中,而後通過攔截器註冊類獲取到攔截器列表,最後將攔截器添加到映射處理器handlerMapping中,供後續使用。

最後看下請求處理的DispatcherServlet#doDispatch方法 (為了看的更清楚一點刪掉了一些代碼)

protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
	HttpServletRequest processedRequest = request;
	// 處理程序執行鏈
	HandlerExecutionChain mappedHandler = null;

	try {
		ModelAndView mv = null;
		Exception dispatchException = null;

		try {
			// Determine handler for the current request.
			// 遍歷handlerMapping獲取能處理request的處理器,mappedHandler里封裝着之前我們定義的攔截器供後續調用
			mappedHandler = getHandler(processedRequest);
			if (mappedHandler == null) {
				noHandlerFound(processedRequest, response);
				return;
			}

			// Determine handler adapter for the current request.
			// 確定處理當前請求的處理適配器 RequestMappingHandlerAdapter
			HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());

			// 執行handler之前應用攔截器執行攔截器的後置方法 返回為false表示請求不合理直接返回了
			if (!mappedHandler.applyPreHandle(processedRequest, response)) {
				return;
			}

			// Actually invoke the handler.
			// 真正執行這個HandlerMethod
			mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
            
			applyDefaultViewName(processedRequest, mv);
			// 執行攔截器的後置方法
			mappedHandler.applyPostHandle(processedRequest, response, mv);
		}
		catch (Exception ex) {
			dispatchException = ex;
		}
		catch (Throwable err) {
			// As of 4.3, we're processing Errors thrown from handler methods as well,
			// making them available for @ExceptionHandler methods and other scenarios.
			dispatchException = new NestedServletException("Handler dispatch failed", err);
		}
		processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
	}
	catch (Exception ex) {
		triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
	}
	catch (Throwable err) {
		triggerAfterCompletion(processedRequest, response, mappedHandler,
				new NestedServletException("Handler processing failed", err));
	}
	finally {

	}
}


#mappedHandler.applyPreHandle
boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
	HandlerInterceptor[] interceptors = getInterceptors();
	if (!ObjectUtils.isEmpty(interceptors)) {
		for (int i = 0; i < interceptors.length; i++) {
			HandlerInterceptor interceptor = interceptors[i];
			// 前置處理為false時
			if (!interceptor.preHandle(request, response, this.handler)) {
				// 觸發攔截器的afterCompletion方法
				triggerAfterCompletion(request, response, null);
				return false;
			}
			this.interceptorIndex = i;
		}
	}
	return true;
}

可以看到再真正執行handler之前會調用mappedHandler.applyPreHandle 方法,遍歷攔截器執行preHandle方法,若返回false則根據先前執行過的攔截器順序倒序執行afterCompletion方法,都通過的話後續執行handler獲取請求結果,再接着執行攔截器的postHandle方法最後執行afterCompletion方法。

Tags: