SpringBoot實戰項目(十六)--攔截器配置及登錄攔截


PS:本文重點在如何在Spring-Boot中使用攔截器,關於攔截器的原理請大家查閱資料了解。

實現自定義攔截器只需要3步: 

1、創建我們自己的攔截器類並實現 HandlerInterceptor 接口。 

2、創建一個Java類繼承WebMvcConfigurerAdapter,並重寫 addInterceptors 方法。 

2、實例化我們自定義的攔截器,然后將對像手動添加到攔截器鏈中。

先來自定義一個MyInterceptor攔截器;
攔截器一般需要繼承HandlerInterceptor接口,並需要實現以下三個接口方法:

 

 

 

 1 package com.beilin.interceptor;
 2 
 3 
 4 
 5 
 6 import org.springframework.web.servlet.HandlerInterceptor;
 7 
 8 
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 import java.util.Date;
12 
13 /**
14  *  攔截器
15  */
16 public class MyInterceptor implements HandlerInterceptor {
17 
18  
19 
20     @Override
21     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
22         //獲取登錄時保存到session的用戶信息
23         SysUser user = (SysUser) request.getSession().getAttribute("user");
24         if (user == null) {
25             //攔截未登錄請求,跳轉到登錄頁面
26             request.getRequestDispatcher("/login").forward(request, response);
27             return false;
28         }
29         return true;
30     }
31 
32     @Override
33     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
34 
35     }
36 
37     @Override
38     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
39         }
40     
41 
42 }

攔截器定義完成后,還需要將攔截器注冊才能生效,並指定該攔截器所攔截的場景。

創建MyWebMvcConfig繼承WebMvcConfigurerAdapter,並重寫 addInterceptors 方法

 

 
         
package com.beilin.interceptor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {

/**
* 將自定義攔截器作為bean寫入配置
* @return
*/
@Bean
public MyInterceptor myInterceptor(){
return new MyInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//攔截處理操作的匹配路徑
//放開靜態攔截
registry.addInterceptor(myInterceptor())
.addPathPatterns("/**") //攔截所有路徑
.excludePathPatterns("/login", "/", "/exit", "/get_cpacha")//排除路徑
.excludePathPatterns("/xadmin/**");//排除靜態資源攔截

}

}
 
        

跟攔截器相關的執行流程如下:

 

 

 測試--直接訪問主頁,攔截器自動攔截所有請求,判斷用戶是否登錄,否--跳轉到登錄頁面

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM