詳解SpringBoot中自定義和配置攔截器的方法
1.SpringBoot版本
本文基于的Spring Boot的版本是2.6.7 。
2.什么是攔截器
Spring MVC中的攔截器(Interceptor)類似于ServLet中的過濾器(Filter),它主要用于攔截用戶請求并作出相應的處理。例如通過攔截器可以進行權限驗證、記錄請求信息的日志、判斷用戶是否登錄等。
3.工作原理
一個攔截器,只有preHandle方法返回true,postHandle、afterCompletion才有可能被執(zhí)行;如果preHandle方法返回false,則該攔截器的postHandle、afterCompletion必然不會被執(zhí)行。攔截器不是Filter,卻實現(xiàn)了Filter的功能,其原理在于:
1.所有的攔截器(Interceptor)和處理器(Handler)都注冊在HandlerMapping中。
2.Spring MVC中所有的請求都是由DispatcherServlet分發(fā)的。
3.當請求進入DispatcherServlet.doDispatch()時候,首先會得到處理該請求的Handler(即Controller中對應的方法)以及所有攔截該請求的攔截器。攔截器就是在這里被調(diào)用開始工作的。
4.攔截器的工作流程
4.1正常流程

4.2中斷流程
如果在Interceptor1.preHandle中報錯或返回false ,那么接下來的流程就會被中斷,但注意被執(zhí)行過的攔截器的afterCompletion仍然會執(zhí)行。
5.應用場景
攔截器本質(zhì)上是面向切面編程(AOP),符合橫切關注點的功能都可以放在攔截器中來實現(xiàn),主要的應用場景包括:
- 登錄驗證,判斷用戶是否登錄。
- 權限驗證,判斷用戶是否有權限訪問資源,如校驗token
- 日志記錄,記錄請求操作日志(用戶ip,訪問時間等),以便統(tǒng)計請求訪問量。
- 處理cookie、本地化、國際化、主題等。
- 性能監(jiān)控,監(jiān)控請求處理時長等。
6.如何自定義一個攔截器
自定義一個攔截器非常簡單,只需要實現(xiàn)HandlerInterceptor這個接口即可,該接口有三個可以實現(xiàn)的方法,如下:
preHandle()方法:改方法會在控制方法前執(zhí)行,器返回值表示是否知道如何寫一個接口。中斷后續(xù)操作。當其返回值為true時,表示繼續(xù)向下執(zhí)行;當其返回值為false時,會中斷后續(xù)的所有操作(包括調(diào)用下一個攔截器和控制器類中的方法執(zhí)行等 )- postHandle()方法: 該方法會在控制器方法調(diào)用之后,且解析視圖之前執(zhí)行??梢酝ㄟ^此方法對請求域中的模型和視圖作出進一步的修改。
- afterCompletion()方法:該方法會在整個請求完成,即視圖渲染結(jié)束之后執(zhí)行??梢酝ㄟ^此方法實現(xiàn)一些資源清理、記錄日志信息等工作。
7.如何使其在Spring Boot中生效
其實想要在Spring Boot生效其實很簡單,只需要定義一個配置類,實現(xiàn)WebMvcConfigurer這個接口,并且實現(xiàn)其中的addInterceptiors()方法即可,代碼演示如下:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private XXX xxx;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//不需要攔截的url
final String[] commonExclude={};
registry.addInterceptor(xxx).excludePathPatterns(commonExclude)
}
}8.實際使用
8.1場景模擬
通過攔截器防止用戶暴力請求連接,使用用戶IP來限制訪問次數(shù) 。達到多少次數(shù)禁止該IP訪問。
8.2思路
記錄用戶IP訪問次數(shù),第一次訪問時在redis中創(chuàng)建一個有效時長1秒的key,當?shù)诙卧L問時key值+1,當值大于等于5時在redis中創(chuàng)建一個5分鐘的key,當攔截器查詢到reids中有當前IP的key值時返回false限制用戶請求接口 。
8.3實現(xiàn)過程
第一步,創(chuàng)建一個攔截器,代碼如下:
@Slf4j
public class IpUrlLimitInterceptor implements HandlerInterceptor {
@Resource
RedisUtils redisUtils;
private static final String LOCK_IP_URL_KEY="lock_ip_";
private static final String IP_URL_REQ_TIME="ip_url_times_";
//訪問次數(shù)限制
private static final long LIMIT_TIMES=5;
//限制時間 秒為單位
private static final int IP_LOCK_TIME=300;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("request請求地址uri={},ip={}",request.getRequestURI(), IpUtils.getRequestIP(request));
if(ipIsLock(IpUtils.getRequestIP(request))){
log.info("ip訪問被禁止={}",IpUtils.getRequestIP(request));
throw new Exception("當前操作過于頻繁,請5分鐘后重試");
}
if (!addRequestTime(IpUtils.getRequestIP(request),request.getRequestURI())){
log.info("當前{}操作過于頻繁,請5分鐘后重試",IpUtils.getRequestIP(request));
throw new Exception("當前操作過于頻繁,請5分鐘后重試");
}
return true;
}
private boolean addRequestTime(String ip, String uri) {
String key = IP_URL_REQ_TIME+ip+uri;
if(redisUtils.hasKey(key)){
long time=redisUtils.incr(key,(long)1);
if(time >=LIMIT_TIMES){
redisUtils.set(LOCK_IP_URL_KEY+ip,IP_LOCK_TIME);
return false;
}
}else {
boolean set = redisUtils.set(key, (long) 1, 1);
}
return true;
}
private boolean ipIsLock(String ip) {
if(redisUtils.hasKey(LOCK_IP_URL_KEY+ip)){
return true;
}
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
第二步,定義一個獲取IP的工具類,代碼如下:
@Slf4j
public class IpUtils {
public static String getRequestIP(HttpServletRequest request){
String ip = request.getHeader("x-forwarded-for");
if(ip != null && ip.length() !=0 && "unknown".equalsIgnoreCase(ip)){
// 多次反向代理后會有多個ip值,第一個ip才是真實ip
if( ip.indexOf(",")!=-1 ){
ip = ip.split(",")[0];
}
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
ip = request.getHeader("Proxy-Client-IP");
log.info("Proxy-Client-IP ip: " + ip);
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
log.info("HTTP_CLIENT_IP ip: " + ip);
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
log.info("HTTP_X_FORWARDED_FOR ip: " + ip);
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Real-IP");
log.info("X-Real-IP ip: " + ip);
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
log.info("getRemoteAddr ip: " + ip);
}
return ip;
}
}第二步,在Spring Boot中配置這個攔截器,代碼如下:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Bean
IpUrlLimitInterceptor getIpUrlLimitInterceptor(){
return new IpUrlLimitInterceptor();
};
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getIpUrlLimitInterceptor()).addPathPatterns("/**");
}
}
8.4效果體驗

9.總結(jié)
該攔截器是全局生效的,可能有些場景某個接口不需要限制,這樣我們可以把這個攔截器改造成注解方式應用。某些接口需要則加上注解即可。
以上就是詳解SpringBoot中自定義和配置攔截器的方法的詳細內(nèi)容,更多關于SpringBoot攔截器的資料請關注腳本之家其它相關文章!
相關文章
解決Feign調(diào)用的GET參數(shù)傳遞的問題
這篇文章主要介紹了解決Feign調(diào)用的GET參數(shù)傳遞的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
windows下使用 intellij idea 編譯 kafka 源碼環(huán)境
這篇文章主要介紹了使用 intellij idea 編譯 kafka 源碼的環(huán)境,本文是基于windows下做的項目演示,需要的朋友可以參考下2021-10-10
解決spring-data-jpa 事物中修改屬性自動更新update問題
這篇文章主要介紹了解決spring-data-jpa 事物中修改屬性自動更新update問題,具有很好的參考價值,希望對大家2021-08-08
解決SpringBoot的@DeleteMapping注解的方法不被調(diào)用問題
這篇文章主要介紹了解決SpringBoot的@DeleteMapping注解的方法不被調(diào)用問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01
Spring Cloud Gateway 內(nèi)存溢出的解決方案
這篇文章主要介紹了Spring Cloud Gateway 內(nèi)存溢出的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07

