草庐IT

SpringWeb 拦截器

monianxd 2023-04-15 原文

前言

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
@Slf4j(topic = "e")
public class CustomInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    log.info("-------------拦截请求:" + request.getRequestURI() + "-------------");
    // 可以根据request设置请求头、或从请求头提取信息等等...
    return true;
  }

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

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
      @Nullable Exception ex) throws Exception {
    log.info("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方法。

有关SpringWeb 拦截器的更多相关文章

  1. ruby-on-rails - 如何找出拦截 'method_missing' 的内容 - 2

    使用Ruby1.8.6/Rails2.3.2我注意到在我的任何ActiveRecord模型类上调用的任何方法都返回nil而不是NoMethodError。除了烦人之外,这还破坏了动态查找器(find_by_name、find_by_id等),因为即使存在记录,它们也总是返回nil。不从ActiveRecord::Base派生的标准类不受影响。有没有办法追踪在ActiveRecord::Base之前拦截method_missing的是什么?更新:切换到1.8.7后,我发现(感谢@MichaelKohl)will_paginate插件首先处理method_missing。但是will_pa

  2. ruby - 如何拦截 ruby​​ 中的方法调用? - 2

    我目前有一个父类(superclass),它有一个函数,我希望所有子类在它的每个函数中调用该函数。该函数的行为应该像rails中的before_filter函数,但我不确定如何去实现before_filter。这是一个例子classSuperclassdefbefore_each_methodputs"BeforeMethod"#thisissupposedtobeinvokedbyeachextendingclass'methodendendclassSubclass 最佳答案 这是一种方法:classSuperclassdefb

  3. ruby - 如何在 Rails 3.0.3 中设置邮件拦截器? - 2

    我正在使用rails3.0.3、ruby1.9.2-p180、邮件(2.2.13)。我正在尝试设置邮件拦截器,但出现以下错误/home/abhimanyu/Aptana_Studio_3_Workspace/delivery_health_dashboard_03/config/initializers/mailer_config.rb:16:in`':uninitializedconstantDevelopmentMailInterceptor(NameError)我该如何解决?我使用的代码如下所示:config/initializer/mailer_config.rbActionM

  4. javascript - Angular 5 提供基于环境的http拦截器 - 2

    我的angular-cli(v1.5.1,angularv5)应用程序中有以下两个环境:开发产品Dev使用模拟数据,我提供了一个http拦截器。Pro使用实时休息api。我如何在dev上提供http拦截器,而不是在pro上?我已经尝试了以下方法,但它不起作用:{provide:HTTP_INTERCEPTORS,useFactory:()=>{if(environment.useMockBackend===true){returnMockHttpInterceptor;}returnfalse;},multi:true} 最佳答案

  5. javascript - 我如何在 Capybara 中测试页面是否*未*重新加载(JavaScript onClick 拦截有效)? - 2

    我正在使用Capybara、Cucumber和Poltergeist。我正在测试附加到表单提交按钮的JavaScript函数,该函数旨在捕获提交事件并阻止它(在后台执行AJAX请求)。使用和不使用AJAX,页面最终看起来都一样,但AJAX方法要快得多,并且不会中断浏览体验等。我可以做些什么来测试表单确实没有提交,并且更改是动态AJAX调用而不是重新加载的结果? 最佳答案 @jules答案的修改版本:describe"Mypage",:jsdoit"reloadswhenitshould"dovisit"/"expect_page_t

  6. javascript - Angular 拦截器和 CORS - 2

    我正在尝试编写一个拦截器以使用Angular向所有HTTP请求添加一个token。我大致使用这里给出的食谱-https://thinkster.io/interceptors因此代码使用了http模块工厂和一个tokenInterceptor()函数。我可以成功地将token作为header添加到请求中-但现在当它通过拦截器时,它会被某种CORS阻塞机制阻塞。我在Chrome控制台中收到此错误-XMLHttpRequestcannotloadhttp://127.0.0.1:/.Responsetopreflightrequestdoesn'tpassaccesscontrolchec

  7. javascript - 拦截 JavaScript 数组访问器 - 2

    我想将一些副作用与每个数组访问器相关联,例如a[i]。例如,如果副作用是向控制台写入消息,则以下程序:vararray=[1,2,3]vartotal=0;for(variinarray){total+=array[i]}console.log(total);应该返回如下输出:1//accessa[0]2//accessa[1]3//accessa[2]6//printoriginaltotal如果我对拦截数组方法push感兴趣,我会使用此博客中的技术post并提供了一个拦截器:var_push=Array.prototype.push;Array.prototype.push=fun

  8. javascript - 拦截来自网页的每个请求 - 2

    是否可以使用javascript拦截从页面发出的每个请求?即单击链接、加载图像、ajax请求... 最佳答案 一句话,没有。没有任何地方可以Hook以获取所有请求。话虽如此,您可以使用javascript在链接上放置事件处理程序,查看图像标签的src属性等。没有“通用”的方式来连接所有AJAX请求-这取决于您使用的库。还有其他需要考虑的,比如CSS背景图片,Flash(如果一个flash文件发出请求怎么办?)。如果可能,您应该使用浏览器本身(例如Firebug)或代理(例如Fiddler)或数据包嗅探器(例如Ethereal...现

  9. javascript - 如何使用在 getScript 回调函数内生成的 URL 打开一个新窗口,并避免弹出窗口拦截器? - 2

    我遇到的问题是,当我尝试执行类似以下代码的操作时,窗口将被弹出窗口阻止程序阻止。我正在使用getScript以便我可以发出跨域请求。我正在使用jQuery1.4.2来执行以下操作。将被阻止的代码示例://Codethatgetsblockedbypop-upblockers$(document).ready(function(){$(".popup").click(function(){$.getScript("URL_To_A_Javascript_File",function(){window.open("dynamicURL","_blank");});});});越过拦截器但未

  10. javascript - 拦截 Jquery AJAX 请求以插入其他变量? - 2

    有什么方法可以拦截通过jquery发出的ajax请求,向其中插入额外的变量吗?我知道.ajaxStart()允许您注册一个回调,该回调在ajax请求开始时触发一个事件,但我正在寻找一种方法来取消该ajax请求,如果它满足某些条件(例如url),在其内容中插入更多变量,然后提交。这是用于第三方软件的插件,其自身代码无法直接更改。编辑:看起来像.ajaxSetup()允许您设置一些与ajaxRequests相关的全局变量。如果我注册了一个beforeSend函数,该函数是否能够取消请求以在满足特定条件时做出不同的请求? 最佳答案 想通了

随机推荐