前言:
用SpringBoot做微服務,必不可少的要處理各種認證、XSS、加解密問題,需要用到過濾器、攔截器、AOP,這裏記錄如何優雅的使用攔截器做請求攔截預處理。
1 實現類
實現HandlerInterceptor接口。
繼承實現HandlerInterceptor接口的實現類,例如:HandlerInterceptorAdapter。
實現AsyncHandlerInterceptor接口。
這裏只展示實現HandlerInterceptor接口和AsyncHandlerInterceptor介紹。
1.1 HandlerInterceptor接口介紹
實現HandlerInterceptor接口提供了三個方法,選擇需要的將他們實現。
(1)preHandle:業務處理請求前被調用,若返回值爲true則攔截放過,若返回值false請求被中止。
(2)postHandle:Controller請求後返回視圖前處理。
(3)afterCompletion:Controller請求返回後處理。
1.2 AsyncHandlerInterceptor接口介紹
AsyncHandlerInterceptor接口比HandlerInterceptor增加了一個方法afterConcurrentHandlingStarted,該接口方法是在使用了異步的方法時調用,例如:controller請求內調用了含@Async的方法,會觸發afterConcurrentHandlingStarted方法執行,觸發前還是先執行preHandle。
2 配置
將攔截器加入到MVC中有三種方式,都是在擴展類中重寫父類方法如下:
(1) @EnableWebMvc + implements WebMvcConfigurer
注意:這種方式會屏蔽掉SpringBoot對SpringMVC的自動配置!
(2)@Configuration + implements WebMvcConfigurer
這種方式最安全,不會屏蔽掉SpringBoot對SpringMVC的自動配置,推薦使用。
(3)@Configuration + extends WebMvcConfigurationSupport
注意:這種方式會屏蔽掉SpringBoot對SpringMVC的自動配置!
2.1 詳解MVC自動配置生效問題
踩坑原因:swagger2訪問失效404
上述方法(1)(2)導致自動配置生效,首先我們看一下自動配置類WebMvcAutoConfiguration的源碼定義:
SpringBoot自動配置類WebMvcAutoConfiguration上有條件註解
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
這個註解的意思是,在項目類中,缺少WebMvcConfigurationSupport類型的bean時,改用自動配置,如果具有該類型bean,自動配置生效,需要在該類型bean中自己重寫需要的配置。
如果不願意重寫配置,可以使用(2)@Configuration + implements WebMvcConfigurer方式配置。
2.2 @Configuration + implements WebMvcConfigurer方式配置
@Configuration
public class WebRequestConfig implements WebMvcConfigurer {
/**
* 實現類
*/
@Autowired
private AppMarkIdInterceptor appMarkIdInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 自定義攔截器,指定攔截路徑和排除攔截路徑
registry.addInterceptor(appMarkIdInterceptor).addPathPatterns("/**");
}