玩轉(zhuǎn)SpringBoot2快速整合攔截器的方法
概述
首先聲明一下,這里所說(shuō)的攔截器是 SpringMVC 的攔截器(HandlerInterceptor)。使用SpringMVC 攔截器需要做如下操作:
創(chuàng)建攔截器類(lèi)需要實(shí)現(xiàn) HandlerInterceptor
在 xml 配置文件中配置該攔截器,具體配置代碼如下:
<mvc:interceptors> <mvc:interceptor> <!-- /test/** 這個(gè)是攔截路徑以/test開(kāi)頭的所有的URL--> <mvc:mapping path="/**"/><!—這個(gè)是攔截所有的路徑--> <!-- 配置攔截器類(lèi)路徑--> <bean class="cn.ljk.springmvc.controller.MyInterceptor"></bean> <!-- 配置不攔截器URL路徑--> <mvc:exclude-mapping path="/fore/**"/> </mvc:interceptor> </mvc:interceptors>
因?yàn)樵赟pringBoot 中沒(méi)有 xml 文件,所以SpringBoot 為我們提供 Java Config 的方式來(lái)配置攔截器。配置方式有2種:
- 繼承 WebMvcConfigurerAdapter (官方已經(jīng)不建議使用)
- 實(shí)現(xiàn) WebMvcConfigurer
接下來(lái)開(kāi)始 SpringBoot 整合攔截器操作詳細(xì)介紹!
整合攔截器實(shí)戰(zhàn)操作
第一步:聲明攔截器類(lèi)
通過(guò)實(shí)現(xiàn) HandlerInterceptor 來(lái)完成。具體代碼如下:
public class LoginInterceptor implements HandlerInterceptor{}
第二步:實(shí)現(xiàn) HandlerInterceptor 3 個(gè)攔截方法
- preHandle:Controller邏輯執(zhí)行之前進(jìn)行攔截
- postHandle:Controller邏輯執(zhí)行完畢但是視圖解析器還未進(jìn)行解析之前進(jìn)行攔截
- afterCompletion:Controller邏輯和視圖解析器執(zhí)行完畢進(jìn)行攔截
實(shí)際開(kāi)發(fā)中 preHandle 使用頻率比較高,postHandle 和 afterCompletion操作相對(duì)比較少。在下面的代碼中 preHandle 方法中定義攔截所有訪問(wèn)項(xiàng)目 url 并進(jìn)行日志信息記錄。
postHandle 中在視圖解析前進(jìn)行攔截,通過(guò) Model 再次添加數(shù)據(jù)到 Request域中。
afterCompletion 暫時(shí)沒(méi)有想到使用場(chǎng)景,如果有使用過(guò)的場(chǎng)景可以在下面評(píng)論區(qū)中進(jìn)行評(píng)論。
攔截器詳細(xì)代碼如下:
public class LoginInterceptor implements HandlerInterceptor{ private Logger log = LoggerFactory.getLogger(LoginInterceptor.class); //ControllerController邏輯執(zhí)行之前 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.info("preHandle...."); String uri = request.getRequestURI(); log.info("uri:"+ uri); if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod) handler; log.info("攔截 Controller:"+ handlerMethod.getBean().getClass().getName()); log.info("攔截方法:"+handlerMethod.getMethod().getName()); } return true; } //Controller邏輯執(zhí)行完畢但是視圖解析器還未進(jìn)行解析之前 @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { log.info("postHandle...."); Map<String,Object>map=modelAndView.getModel(); map.put("msg","postHandle add msg"); } //Controller邏輯和視圖解析器執(zhí)行完畢 @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { log.info("afterCompletion...."); } }
第三步:Java Config 的方式來(lái)配置攔截器
繼承 WebMvcConfigurerAdapter 方式
通過(guò)繼承 WebMvcConfigurerAdapter 并重寫(xiě) addInterceptors方法,通過(guò)其參數(shù) InterceptorRegistry 將攔截器注入到 Spring的上下文中。
另外攔截路徑和不攔截的路徑通過(guò)InterceptorRegistry 的 addPathPatterns 和 excludePathPatterns 方法進(jìn)行設(shè)置。
繼承 WebMvcConfigurerAdapter 方式官方已經(jīng)不建議使用,因?yàn)楣俜揭褜?WebMvcConfigurerAdapter 標(biāo)記為@Deprecated 了。
@Deprecated public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {
繼承 WebMvcConfigurerAdapter 方式具體代碼如下:
@Configuration public class InterceptorConfigByExtendsWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter{ @Bean public LoginInterceptor loginInterceptor(){ return new LoginInterceptor(); } public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginInterceptor()).addPathPatterns("/**").excludePathPatterns("/*.html"); } }
實(shí)現(xiàn) WebMvcConfigurer 方式
通過(guò)實(shí)現(xiàn) WebMvcConfigurer 接口 并實(shí)現(xiàn) addInterceptors方法,其他操作和繼承 WebMvcConfigurerAdapter 方式一樣。具體代碼如下:
@Configuration public class InterceptorConfigByImplWebMvcConfigurer implements WebMvcConfigurer{ @Bean public LoginInterceptor loginInterceptor(){ return new LoginInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginInterceptor()).addPathPatterns("/**").excludePathPatterns("/*.html"); } }
測(cè)試
編寫(xiě)普通Controller,具體代碼如下:
@Controller public class IndexController { @GetMapping("/index") public String index(ModelAndView modelAndView){ return "index"; } }
在 src/main/resource 下的 templates 目錄下創(chuàng)建 IndexController 訪問(wèn)頁(yè)面 index.ftl, 代碼如下:
<h1>${msg}</h1>
由于我這里使用的是 Freemarker 當(dāng)頁(yè)面使用,所以需要引入 freemarker starter依賴(lài),具體點(diǎn)如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
通過(guò)游覽器訪問(wèn) localhost:8080/sbe/index,具體訪問(wèn)效果如下:
如上圖所示在視圖解析前通過(guò) Model 再次添加數(shù)據(jù)到 Request域中的msg 成功顯示出來(lái)了!
日志輸出信息如下:(攔截地址和攔截Controller 和具體方法進(jìn)行日志輸出)
2019-09-24 15:53:04.144 INFO 7732 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/sbe] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-09-24 15:53:04.145 INFO 7732 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2019-09-24 15:53:04.153 INFO 7732 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 8 ms
2019-09-24 15:53:04.155 INFO 7732 --- [nio-8080-exec-1] c.lijunkui.interceptor.LoginInterceptor : preHandle....
2019-09-24 15:53:04.155 INFO 7732 --- [nio-8080-exec-1] c.lijunkui.interceptor.LoginInterceptor : uri:/sbe/index
2019-09-24 15:53:04.155 INFO 7732 --- [nio-8080-exec-1] c.lijunkui.interceptor.LoginInterceptor : 攔截 Controller:cn.lijunkui.controller.IndexController
2019-09-24 15:53:04.155 INFO 7732 --- [nio-8080-exec-1] c.lijunkui.interceptor.LoginInterceptor : 攔截方法:index
2019-09-24 15:53:04.156 INFO 7732 --- [nio-8080-exec-1] c.lijunkui.interceptor.LoginInterceptor : postHandle....
2019-09-24 15:53:04.161 INFO 7732 --- [nio-8080-exec-1] c.lijunkui.interceptor.LoginInterceptor : afterCompletion....
小結(jié)
SpringBoot 2 整合攔截器和整合 Filter的操作很像,都是通過(guò)一個(gè)注冊(cè)類(lèi)將其注入到Spring的上下文中,只不過(guò)Filter使用的是 FilterRegistrationBean 而 攔截器使用的是 InterceptorRegistry。
個(gè)人覺(jué)得比使用 xml 配置的方式更為簡(jiǎn)單了,如果你還沒(méi)有在 SpringBoot 項(xiàng)目中使用過(guò)攔截器,趕快來(lái)操作一下吧!
代碼示例
具體代碼示例請(qǐng)?jiān)谖业腉itHub 倉(cāng)庫(kù) springbootexamples 中模塊名為 spring-boot-2.x-interceptor 項(xiàng)目中進(jìn)行查看
GitHub:https://github.com/zhuoqianmingyue/springbootexamples
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- SpringBoot 過(guò)濾器、攔截器、監(jiān)聽(tīng)器對(duì)比及使用場(chǎng)景分析
- SpringBoot登錄用戶權(quán)限攔截器
- SpringBoot 攔截器和自定義注解判斷請(qǐng)求是否合法
- SpringBoot配置攔截器的示例
- SpringBoot之HandlerInterceptor攔截器的使用詳解
- 解決Springboot @WebFilter攔截器未生效問(wèn)題
- springboot攔截器過(guò)濾token,并返回結(jié)果及異常處理操作
- SpringBoot攔截器如何獲取http請(qǐng)求參數(shù)
- SpringBoot攔截器原理解析及使用方法
- SpringBoot配置攔截器方式實(shí)例代碼
- SpringBoot攔截器Filter的使用方法詳解
- springboot創(chuàng)建攔截器過(guò)程圖解
- SpringBoot實(shí)現(xiàn)攔截器、過(guò)濾器、監(jiān)聽(tīng)器過(guò)程解析
- Springboot引入攔截器并放行swagger代碼實(shí)例
- Springboot項(xiàng)目使用攔截器方法詳解
- SpringBoot攔截器實(shí)現(xiàn)登錄攔截的方法示例
- SpringBoot實(shí)現(xiàn)過(guò)濾器、攔截器與切片的實(shí)現(xiàn)和區(qū)別
- 教你用Springboot實(shí)現(xiàn)攔截器獲取header內(nèi)容
相關(guān)文章
Spring實(shí)現(xiàn)動(dòng)態(tài)切換多數(shù)據(jù)源的解決方案
這篇文章主要給大家介紹了Spring實(shí)現(xiàn)動(dòng)態(tài)切換多數(shù)據(jù)源的解決方案,文中給出了詳細(xì)的介紹和示例代碼,相信對(duì)大家的理解和學(xué)習(xí)具有一定的參考借鑒價(jià)值,有需要的朋友可以參考學(xué)習(xí),下面來(lái)一起看看吧。2017-01-01SpringBoot定時(shí)任務(wù)調(diào)度與爬蟲(chóng)的配置實(shí)現(xiàn)
這篇文章主要介紹了SpringBoot定時(shí)任務(wù)調(diào)度與爬蟲(chóng)的實(shí)現(xiàn),使用webmagic開(kāi)發(fā)爬蟲(chóng),繼承PageProcessor接口編寫(xiě)自己的處理類(lèi),process是定制爬蟲(chóng)邏輯的核心接口,在這里編寫(xiě)抽取邏輯,具體實(shí)現(xiàn)配置過(guò)程跟隨小編一起看看吧2022-01-01詳解Java編寫(xiě)算法時(shí)如何加快讀寫(xiě)數(shù)據(jù)速度
這篇文章主要為大家詳細(xì)介紹了Java在編寫(xiě)算法時(shí)如何加快讀寫(xiě)數(shù)據(jù)速度,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-03-03Java Map如何根據(jù)key取value以及不指定key取出所有的value
這篇文章主要介紹了Java Map如何根據(jù)key取value以及不指定key取出所有的value,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09SpringBoot統(tǒng)一響應(yīng)格式及統(tǒng)一異常處理
在我們開(kāi)發(fā)SpringBoot后端服務(wù)時(shí),一般需要給前端統(tǒng)一響應(yīng)格式,本文主要介紹了SpringBoot統(tǒng)一響應(yīng)格式及統(tǒng)一異常處理2023-05-05JFinal 調(diào)用存儲(chǔ)過(guò)程的步驟
這篇文章主要介紹了JFinal 調(diào)用存儲(chǔ)過(guò)程的步驟,幫助大家更好的理解和學(xué)習(xí)使用JFinal,感興趣的朋友可以了解下2021-03-03