springboot filter實(shí)現(xiàn)請(qǐng)求響應(yīng)全鏈路攔截
一、為什么你需要這個(gè)過濾器??
日志痛點(diǎn):
- 請(qǐng)求參數(shù)散落在各處?
- 響應(yīng)數(shù)據(jù)無法統(tǒng)一記錄?
- 日志與業(yè)務(wù)代碼嚴(yán)重耦合?
??解決方案??: 一個(gè)Filter同時(shí)攔截請(qǐng)求和響應(yīng),實(shí)現(xiàn)??日志采集自動(dòng)化??!
??二、核心實(shí)現(xiàn):一個(gè)Filter搞定雙向數(shù)據(jù)流??
過濾器設(shè)計(jì)亮點(diǎn)??
- 請(qǐng)求參數(shù)捕獲??:GET/POST參數(shù)統(tǒng)一解析
- 響應(yīng)結(jié)果截取??:支持JSON/XML等文本響應(yīng)
- 零代碼侵入??:不修改業(yè)務(wù)代碼即可植入監(jiān)控
- ??JDK1.8完美兼容??:無任何新特性依賴
??三、完整代碼實(shí)現(xiàn)??
??1. 過濾器核心代碼(可直接復(fù)制)??
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class RequestResponseLogFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain)
throws ServletException, IOException {
// 包裝請(qǐng)求響應(yīng)對(duì)象
ContentCachingRequestWrapper wrappedRequest =
new ContentCachingRequestWrapper(request);
ContentCachingResponseWrapper wrappedResponse =
new ContentCachingResponseWrapper(response);
try {
// 執(zhí)行后續(xù)過濾器鏈
filterChain.doFilter(wrappedRequest, wrappedResponse);
// 記錄日志(核心邏輯)
logRequest(wrappedRequest);
logResponse(wrappedResponse);
} finally {
// 必須執(zhí)行響應(yīng)回寫
wrappedResponse.copyBodyToResponse();
}
}
// 請(qǐng)求日志方法
private void logRequest(ContentCachingRequestWrapper request) {
String method = request.getMethod();
String url = request.getRequestURL().toString();
String params = getRequestParams(request);
System.out.printf("[請(qǐng)求] %s %s | 參數(shù)=%s%n", method, url, params);
}
// 響應(yīng)日志方法
private void logResponse(ContentCachingResponseWrapper response) throws IOException {
int status = response.getStatus();
String body = getResponseBody(response);
System.out.printf("[響應(yīng)] 狀態(tài)碼=%d | 內(nèi)容=%s%n", status, body);
}
// 獲取請(qǐng)求參數(shù)工具方法
private String getRequestParams(ContentCachingRequestWrapper request) {
try {
if ("GET".equalsIgnoreCase(request.getMethod())) {
return request.getQueryString();
} else {
byte[] body = request.getContentAsByteArray();
return new String(body, request.getCharacterEncoding());
}
} catch (Exception e) {
return "[參數(shù)解析失敗]";
}
}
// 獲取響應(yīng)內(nèi)容工具方法
private String getResponseBody(ContentCachingResponseWrapper response) throws IOException {
byte[] content = response.getContentAsByteArray();
return new String(content, response.getCharacterEncoding());
}
@Override
public void init(FilterConfig filterConfig) {}
@Override
public void destroy() {}
}
四、過濾器添加三步走??
??1. 添加依賴(Maven配置)??
<!-- 核心包裝類 -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-catalina</artifactId>
<version>9.0.65</version>
</dependency>
??2. web.xml配置??(傳統(tǒng)項(xiàng)目)
<filter>
<filter-name>RequestResponseLogFilter</filter-name>
<filter-class>com.example.RequestResponseLogFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>RequestResponseLogFilter</filter-name>
<url-pattern>/*</url-pattern> <!-- 攔截所有請(qǐng)求 -->
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
????3. Spring Boot集成??(新項(xiàng)目推薦)
@Bean
public FilterRegistrationBean<RequestResponseLogFilter> logFilter(){
FilterRegistrationBean<RequestResponseLogFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new RequestResponseLogFilter());
registrationBean.addUrlPatterns("/*");
return registrationBean;
}
五、運(yùn)行效果演示??
[REQUEST] POST http://api/user/login | 參數(shù)=username=admin&password=123456 | 時(shí)間=Wed Oct 05 14:30:00 CST 2023
[RESPONSE] 狀態(tài)碼=200 | 響應(yīng)內(nèi)容={"code":0,"msg":"登錄成功"} | 耗時(shí)=120ms
六、必須注意的6大事項(xiàng)??
1.內(nèi)存溢出風(fēng)險(xiǎn)??
攔截大文件上傳時(shí)(>1MB)會(huì)占用大量內(nèi)存
解決方案:限制緩存大小
// 在構(gòu)造方法中設(shè)置最大緩存 new ContentCachingRequestWrapper(request, 1024 * 1024); // 1MB
2.??編碼兼容性問題??
請(qǐng)求參數(shù)亂碼常因缺少編碼設(shè)置導(dǎo)致
強(qiáng)制設(shè)置編碼(在Filter頭部添加)
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
3.??響應(yīng)流二次讀取??
原始響應(yīng)流只能讀取一次,必須使用包裝類
錯(cuò)誤寫法:直接使用原始response.getWriter()
4.敏感信息泄露??
密碼等字段需過濾(正則替換示例)
params.replaceAll("password=\\w+", "password=?**?*");
5.性能損耗控制??
高并發(fā)場(chǎng)景建議異步記錄日志
CompletableFuture.runAsync(() -> log.info(logContent));
6.HTTPS支持??
確保Tomcat配置正確:
<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
SSLEnabled="true" scheme="https" secure="true"/>
七、進(jìn)階玩法??
組合使用??:
搭配Spring AOP實(shí)現(xiàn)方法級(jí)日志
結(jié)合Redis實(shí)現(xiàn)請(qǐng)求限流
數(shù)據(jù)分析??:
-- 日志分析SQL示例
SELECT
request_uri,
COUNT(*) as total,
AVG(response_time) as avg_time
FROM access_log
WHERE status >= 500
GROUP BY request_uri;
總結(jié)??
一個(gè)優(yōu)秀的Filter就像「數(shù)字監(jiān)控?cái)z像頭」,默默記錄系統(tǒng)運(yùn)行軌跡。通過本文的方案,你可以:
- 統(tǒng)一管理所有請(qǐng)求響應(yīng)日志
- 零成本實(shí)現(xiàn)全鏈路追蹤
- 靈活擴(kuò)展監(jiān)控維度
到此這篇關(guān)于springboot filter實(shí)現(xiàn)請(qǐng)求響應(yīng)全鏈路攔截的文章就介紹到這了,更多相關(guān)springboot filter請(qǐng)求攔截內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java程序運(yùn)行之JDK,指令javac java解讀
這篇文章主要介紹了Java程序運(yùn)行之JDK,指令javac java,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01
MyBatis的通俗理解:SqlSession.getMapper()源碼解讀
這篇文章主要介紹了MyBatis的通俗理解:SqlSession.getMapper()源碼解讀,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
使用@SpringBootTest注解進(jìn)行單元測(cè)試
這篇文章主要介紹了使用@SpringBootTest注解進(jìn)行單元測(cè)試,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09
java使用Base64實(shí)現(xiàn)文件加密解密
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)Base64給文件加密、解密,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-03-03
java使用listIterator逆序arraylist示例分享
對(duì)于列表而言,除了Iterator,還提供了一個(gè)功能更加強(qiáng)大的ListIterator。它可以實(shí)現(xiàn)逆序遍歷列表中的元素。本示例將使用其逆序遍歷ArrayList2014-02-02
idea使用pagehelper實(shí)現(xiàn)后端分頁功能的步驟詳解
這篇文章主要介紹了idea使用pagehelper實(shí)現(xiàn)后端分頁功能的步驟,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09
mybatis如何實(shí)現(xiàn)in傳入數(shù)組查詢
這篇文章主要介紹了mybatis如何實(shí)現(xiàn)in傳入數(shù)組查詢方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10

