spring boot 使用攔截器
1.創建攔截器類,繼承HandlerInterceptor
2.注冊攔截器,指定攔截規則
spring framework 中的攔截器類需要繼承與HandlerInterceptor,spring boot也是一致的
package com.tons.intercept;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class RecordIntercept implements HandlerInterceptor {
/*
request 請求物件
response 回應物件
handler 請求處理器,可以強轉成HandlerMethod使用(可獲取處理方法的相關資訊),
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 獲取路由
String remoteAddr = request.getRemoteAddr();
// 獲取訪問路徑 http:localhost:80/ 后面的url部分
String url = request.getRequestURI();
// 列印
log.debug("{}訪問了[{}]",remoteAddr,url);
// 回傳true 放行,false不放行
return true;
}
}
注冊攔截器,指定攔截規則
package com.tons.config;
import com.tons.intercept.PowerIntercept;
import com.tons.intercept.RecordIntercept;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Arrays;
import java.util.List;
/**
* 配置攔截器
*/
@Configuration
public class InterceptConfig implements WebMvcConfigurer {
private static final List<String> STATIC_PATH = Arrays.asList("/","/index","/css/**","/js/**","/img/**","/media/**","/vendors/**","/element-ui/**","/temp/**","/public/**","/json/**","/favicon.ico","/error");
/**
* 配置攔截器
* @param registry 攔截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
WebMvcConfigurer.super.addInterceptors(registry);
//addPathPatterns 攔截路徑
//excludePathPatterns 不攔截路徑
// /**代表當前目錄下所有資源(包含其內部子資源)
registry.addInterceptor(new RecordIntercept()).addPathPatterns("/**").excludePathPatterns(STATIC_PATH);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/539830.html
標籤:其他
上一篇:用狀態機實作串口多位元組資料發送
下一篇:Python函式的引數
