Real-World Analogy: Airport Security Checkpoint
Imagine entering an airport. Before you can reach your gate (Spring Controller), security officers check your passport, scan your luggage, and stamp your boarding pass. If your passport is invalid, you get turned away at the entrance! A Servlet Filter is that airport security checkpoint operating at the raw HTTP layer.
What is a Servlet Filter?
A Servlet Filter is a low-level Jakarta EE component that intercepts every incoming HTTP request BEFORE it reaches Spring Framework's DispatcherServlet, and intercepts every HTTP response BEFORE it returns to the user's browser.
Common Use Cases for Filters
- 🔒 Security & CORS: Adding Cross-Origin Resource Sharing headers (`Access-Control-Allow-Origin`).
- ⏱️ Request Timing & Metrics: Logging total execution time of incoming requests.
- 🗝️ Token Extraction: Extracting JWT Bearer tokens from the `Authorization` header.
Complete Beginner Code Example:
RequestLoggingFilter.java
package com.anujsingh.digitalguru.filter;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class RequestLoggingFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
long startTime = System.currentTimeMillis();
System.out.println("[FILTER] Incoming Request: " + req.getMethod() + " " + req.getRequestURI());
// Pass control to the next filter or servlet in the chain
chain.doFilter(request, response);
long duration = System.currentTimeMillis() - startTime;
System.out.println("[FILTER] Request Completed in " + duration + " ms");
}
}
Line-by-Line Breakdown:
implements Filter: Implements the standard Jakarta Servlet Filter interface.chain.doFilter(request, response): Critical method call that forwards the request down the chain to the next filter or controller!System.currentTimeMillis(): Calculates total round-trip processing time.