在進行項目開發的時候使用springboot框架用到攔截器時發現2.0以后原來的抽象類WebMvcConfigurerAdapter已經過時了,去官網查文檔2.x版本要實現攔截器功能改為需要繼承WebMvcConfigurer接口。
實現攔截器大致分為兩步
-
創建我們自己的攔截器類並實現 HandlerInterceptor 接口
//創建攔截器BackInterceptor並實現接口HandlerInterceptor public class BackInterceptor implements HandlerInterceptor { //重寫preHandle方法 @Override public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception { //判斷session里是否有user if (null == request.getSession().getAttribute("user")) { return false; } return true; } }
-
其實重寫WebMvcConfigurerAdapter中的addInterceptors方法把自定義的攔截器類添加進來即可
//創建一個實現WebMvcConfigurer接口的類 public class MyWebMvcConfigurerAdapter implements WebMvcConfigurer { //獲取攔截器的Bean @Bean public HandlerInterceptor getBackInterceptor() { return new BackInterceptor(); } /** * 重寫addInterceptors方法 * addPathPatterns:需要攔截的訪問路徑 * excludePathPatterns:不需要攔截的路徑, * String數組類型可以寫多個用","分割 */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(getBackInterceptor()).addPathPatterns("/admin/**").excludePathPatterns("/toLogin", "/admin/login"); } }
攔截器測試,攔截了addPathPatterns("/admin/**")也就是admin下的所有資源
可以看到訪問路徑http://localhost:10010/admin后顯示的是錯誤頁面
下面試一下訪問不需要攔截的路徑excludePathPatterns("/toLogin")
http://localhost:10010/toLogin
成功訪問到登錄頁面