SpringBoot配置攔截器實(shí)現(xiàn)過程詳解
如何配置攔截器
step1: 自定義攔截器
/** * 自定義攔截器 */ public class MyInterceptor implements HandlerInterceptor { private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class); /** * 在請求匹配controller之前執(zhí)行,返回true才行進(jìn)行下一步 * @param request * @param response * @param handler * @return * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return false; } /** * 已經(jīng)執(zhí)行完controller了,但是還沒有進(jìn)入視圖渲染 * @param request * @param response * @param handler * @param modelAndView * @throws Exception */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } /** * 視圖也渲染完了,此時(shí)我可以做一些清理工作了 * @param request * @param response * @param handler * @param ex * @throws Exception */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
step2:配置攔截器
@Configuration public class MyInterceptorConfig extends WebMvcConfigurationSupport { @Override protected void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**"); // 攔截所有內(nèi)容:/** 攔截部分內(nèi)容:/admin/** super.addInterceptors(registry); } }
攔截器設(shè)置容易出現(xiàn)的問題
靜態(tài)資源被攔截
MyInterceptorConfig 繼承 WebMvcConfigurationSupport類時(shí),會(huì)導(dǎo)致resources/static下的靜態(tài)資源也被攔截,如果我們不想靜態(tài)資源被攔截,可以嘗試以下兩種方法。
/** * 在MyInterceptorConfig中重寫addResourceHandlers方法,重新指定靜態(tài)資源 * 推薦在前后端分離時(shí)使用,后臺(tái)不需要訪問靜態(tài)資源 * * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**").addResourceLocations( "classpath:/static/"); super.addResourceHandlers(registry); }
/** * 將MyInterceptorConfig類由繼承WebMvcConfigurationSupport改為實(shí)現(xiàn)WebMvcConfigurer * 推薦在非前后端分離時(shí)使用,后臺(tái)需要訪問靜態(tài)資源 * */ @Configuration public class MyInterceptorConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**"); // 攔截所有內(nèi)容:/** 攔截部分內(nèi)容:/admin/** } }
如何取消攔截操作
step1:自定義注解
/** * 自定義注解用來指定某個(gè)方法不用攔截 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface UnInterception { }
step2:修改攔截器MyInterceptor中的preHandle方法
/** * 在請求匹配controller之前執(zhí)行 * @param request * @param response * @param handler * @return * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { UnInterception unInterception = method.getAnnotation(UnInterception.class); if(null != unInterception) { logger.info("不需要攔截,可以執(zhí)行"); return true; } // 返回true才會(huì)執(zhí)行方法,返回false不會(huì)執(zhí)行 return false; }
step3:在不需要攔截的controller上加上UnInterception注解
@Controller @RequestMapping("/interceptor") public class InterceptorController { @UnInterception @RequestMapping("/test") public String test() { return "hello"; } }
實(shí)例-登錄驗(yàn)證
用攔截器實(shí)現(xiàn)一個(gè)登錄驗(yàn)證功能
step1:自定義攔截器
import com.kimmel.course13.annotation.UnInterception; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.lang.reflect.Method; /** * 自定義攔截器 */ public class MyInterceptor implements HandlerInterceptor { private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class); /** * 在請求匹配controller之前執(zhí)行 * @param request * @param response * @param handler * @return * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); String methodName = method.getName(); // 判斷用戶有沒有登錄,一般登錄之后的用戶都有一個(gè)對應(yīng)的token UnInterception unInterception = method.getAnnotation(UnInterception.class); String token = request.getParameter("token"); if (null == token || "".equals(token)) { logger.info("用戶未登錄,沒有權(quán)限執(zhí)行{}請登錄", methodName); return false; } // 返回true才會(huì)執(zhí)行方法,返回false不會(huì)執(zhí)行 return true; } /** * 已經(jīng)執(zhí)行完controller了,但是還沒有進(jìn)入視圖渲染 * @param request * @param response * @param handler * @param modelAndView * @throws Exception */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); String methodName = method.getName(); logger.info("已經(jīng)執(zhí)行完{}了,但是還沒有進(jìn)入視圖渲染", methodName); } /** * 視圖也渲染完了,此時(shí)我可以做一些清理工作了 * @param request * @param response * @param handler * @param ex * @throws Exception */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { logger.info("視圖也渲染完了,此時(shí)我可以做一些清理工作了"); } }
step2:配置攔截器
import com.kimmel.course13.Interceptor.MyInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; @Configuration public class MyInterceptorConfig extends WebMvcConfigurationSupport { @Override protected void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**"); // 攔截所有內(nèi)容:/** 攔截部分內(nèi)容:/admin/** super.addInterceptors(registry); } /** * 發(fā)現(xiàn)如果繼承了WebMvcConfigurationSupport,則在yml中配置的相關(guān)內(nèi)容會(huì)失效。 需要重新指定靜態(tài)資源 * * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**").addResourceLocations( "classpath:/static/"); registry.addResourceHandler("swagger-ui.html").addResourceLocations( "classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations( "classpath:/META-INF/resources/webjars/"); super.addResourceHandlers(registry); } }
step3:自定義測試controller
@Controller @RequestMapping("/interceptor") public class InterceptorController { @RequestMapping("/test") public String test() { return "hello"; } }
step4:測試
進(jìn)入瀏覽器,輸入http://localhost:8080/interceptor/test
結(jié)果:無法進(jìn)入,日志:用戶未登錄,沒有權(quán)限執(zhí)行 test 請登錄
進(jìn)入瀏覽器,輸入http://localhost:8080/interceptor/test?token=1
結(jié)果:成功進(jìn)入hello.html
到此這篇關(guān)于SpringBoot配置攔截器實(shí)現(xiàn)過程詳解的文章就介紹到這了,更多相關(guān)SpringBoot配置攔截器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot后端接收參數(shù)優(yōu)化代碼示例(統(tǒng)一處理前端參數(shù))
使用Spring Boot開發(fā)API的時(shí)候,讀取請求參數(shù)是服務(wù)端編碼中最基本的一項(xiàng)操作,下面這篇文章主要給大家介紹了關(guān)于SpringBoot后端接收參數(shù)優(yōu)化(統(tǒng)一處理前端參數(shù))的相關(guān)資料,需要的朋友可以參考下2024-07-07如何解決EasyExcel導(dǎo)出文件LocalDateTime報(bào)錯(cuò)問題
這篇文章主要介紹了如何解決EasyExcel導(dǎo)出文件LocalDateTime報(bào)錯(cuò)問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06Java實(shí)現(xiàn)文件名倒序排序的技術(shù)指南
在實(shí)際開發(fā)過程中,我們經(jīng)常需要對文件進(jìn)行操作和處理,一個(gè)常見的需求是按文件名倒序排列文件列表,以便于文件的管理和查找,本文將介紹如何在Java中實(shí)現(xiàn)文件名倒序排序,并提供詳細(xì)的代碼案例,需要的朋友可以參考下2024-08-08JAVA構(gòu)造方法/構(gòu)造器以及this使用方式
這篇文章主要介紹了JAVA構(gòu)造方法/構(gòu)造器以及this使用方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03SpringBoot?@DS注解實(shí)現(xiàn)多數(shù)據(jù)源配置以及問題解決辦法
這篇文章主要給大家介紹了關(guān)于SpringBoot?@DS注解實(shí)現(xiàn)多數(shù)據(jù)源配置以及問題解決辦法,所謂多數(shù)據(jù)源就是一個(gè)Java EE項(xiàng)目中采用了不同數(shù)據(jù)庫實(shí)例中的多個(gè)庫,或者是同一個(gè)數(shù)據(jù)庫實(shí)例中的多個(gè)不同庫,需要的朋友可以參考下2023-11-11SpringMVC?RESTFul實(shí)戰(zhàn)案例訪問首頁
這篇文章主要為大家介紹了SpringMVC?RESTFul實(shí)戰(zhàn)案例訪問首頁,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05