SoFunction
Updated on 2025-04-14

springboot filter implements full-link interception request response

1. Why do you need this filter? ​

Log pain points:

  • Request parameters are scattered everywhere?
  • Can't the response data be recorded uniformly?
  • Are logs severely coupled with business code?

Solution: A Filter intercepts requests and responses simultaneously to achieve log collection automation!

​​2. Core implementation: A Filter handles two-way data flow

Highlights of filter design

  • Request parameter capture: Unified analysis of GET/POST parameters
  • Response result interception: Supports text responses such as JSON/XML
  • Zero code intrusion: no modification of business code can be implanted
  • JDK1.8 is perfectly compatible: no new features dependencies

​​3. Complete code implementation

​​1. Filter core code (can be copied directly)​​

import ;
import ;
import ;
import ;
import ;
import ;

public class RequestResponseLogFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, 
                                    HttpServletResponse response, 
                                    FilterChain filterChain)
            throws ServletException, IOException {
        
        // Package the request response object        ContentCachingRequestWrapper wrappedRequest = 
            new ContentCachingRequestWrapper(request);
        ContentCachingResponseWrapper wrappedResponse = 
            new ContentCachingResponseWrapper(response);

        try {
            // Execute subsequent filter chains            (wrappedRequest, wrappedResponse);
            
            // Logging (core logic)            logRequest(wrappedRequest);
            logResponse(wrappedResponse);
            
        } finally {
            // Response reply must be performed            ();
        }
    }

    // Request log method    private void logRequest(ContentCachingRequestWrapper request) {
        String method = ();
        String url = ().toString();
        String params = getRequestParams(request);
        
        ("[ask] %s %s | parameter=%s%n", method, url, params);
    }

    // Response log method    private void logResponse(ContentCachingResponseWrapper response) throws IOException {
        int status = ();
        String body = getResponseBody(response);
        
        ("[response] Status code=%d | content=%s%n", status, body);
    }

    
    // Get request parameters tool method    private String getRequestParams(ContentCachingRequestWrapper request) {
        try {
            if ("GET".equalsIgnoreCase(())) {
                return ();
            } else {
                byte[] body = ();
                return new String(body, ());
            }
        } catch (Exception e) {
            return "[Parameter parsing failed]";
        }
    }

    // Method for obtaining response content    private String getResponseBody(ContentCachingResponseWrapper response) throws IOException {
        byte[] content = ();
        return new String(content, ());
    }

    @Override
    public void init(FilterConfig filterConfig) {}

    @Override
    public void destroy() {}
}

4. Add filters in three steps​​

​​1. Add dependencies (Maven configuration)​​

<!-- Core packaging -->
<dependency>
    <groupId></groupId>
    <artifactId>tomcat-catalina</artifactId>
    <version>9.0.65</version>
</dependency>

​​2. Configuration (traditional project)

<filter>
    <filter-name>RequestResponseLogFilter</filter-name>
    <filter-class></filter-class>
</filter>

<filter-mapping>
    <filter-name>RequestResponseLogFilter</filter-name>
    <url-pattern>/*</url-pattern> <!-- Intercept all requests -->
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

​​​​3. Spring Boot Integration (New Project Recommendation)

@Bean
public FilterRegistrationBean<RequestResponseLogFilter> logFilter(){
    FilterRegistrationBean<RequestResponseLogFilter> registrationBean = new FilterRegistrationBean<>();
    (new RequestResponseLogFilter());
    ("/*");
    return registrationBean;
}

5. Running effect demonstration

[REQUEST] POST http://api/user/login | Parameters =username=admin&password=123456 | Time=Wed Oct 05 14:30:00 CST 2023
[RESPONSE] Status code=200 | Response content={"code":0,"msg":"Login successfully"} | Time taken=120ms

6. 6 major things to pay attention to

1. Memory overflow risk

Intercept large files to upload (>1MB) will take up a lot of memory

Solution: Limit cache size

// Set the maximum cache in the constructornew ContentCachingRequestWrapper(request, 1024 * 1024); // 1MB

2. Coding compatibility issues

The garbled code of the request parameters is often caused by the lack of encoding settings.

Force encoding (added in Filter header)

("UTF-8");
("UTF-8");

3. Response stream secondary read

The original response stream can only be read once, and the wrapper class must be used.

Error writing: Use original() directly

4. Sensitive information leakage

Fields such as password need to be filtered (regular replacement example)

("password=\\w+", "password=​**​*");

5. Performance loss control

High concurrency scenarios suggest logging asynchronously

(() -> (logContent));

Support

Make sure Tomcat is configured correctly:

<Connector port="8443" protocol=".http11.Http11NioProtocol"
           SSLEnabled="true" scheme="https" secure="true"/>

7. Advanced gameplay

Combination use:

Implement method level log with Spring AOP

Combined with Redis to implement request current limit

Data Analysis:

-- Log AnalysisSQLExample
SELECT 
    request_uri, 
    COUNT(*) as total,
    AVG(response_time) as avg_time 
FROM access_log 
WHERE status &gt;= 500 
GROUP BY request_uri;

Summary

An excellent Filter is like a "digital surveillance camera", silently recording the system's operating trajectory. Through this article's solution, you can:

  • Unified management of all request response logs
  • Realize full-link tracking at zero cost
  • Flexible expansion of monitoring dimensions

This is the article about springboot filter implementing request response full-link interception. For more related contents of springboot filter request interception, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!