Fading Coder

One Final Commit for the Last Sprint

Home > Tools > Content

Request Processing Gateways: Comparing Servlet Filters and Spring Interceptors

Tools 1

Servlet Filters: The Perimeter Checkpoint

Picture a customs checkpoint at an international border. Every vehicle crossing the boundary undergoes inspection regardless of its final destination. Officers verify travel documents, scan cargo, and determine entry eligibility before allowing passage into the country. Servlet Filters operate with similar authority at the application boundary.

Filters function within the Java Servlet specification, making them container-agnostic components compatible with any Jakarta EE web application. Positioned at the outermost layer of the request processing pipeline, they intercept all inbound HTTP traffic before it reaches the DispatcherServlet or any specific endpoint. These components can inspect, modify, or terminate requests based on headers, URL patterns, or HTTP methods. Likewise, they possess the capability to transform outbound responses before transmission to clients.

@Component
public class SecurityCheckpoint implements Filter {
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, 
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpReq = (HttpServletRequest) request;
        HttpServletResponse httpRes = (HttpServletResponse) response;
        
        String authToken = httpReq.getHeader("Authorization");
        if (isInvalid(authToken)) {
            httpRes.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        
        chain.doFilter(request, response);
    }
    
    private boolean isInvalid(String token) {
        return token == null || !token.startsWith("Bearer ");
    }
}

Spring Interceptors: The Internal Surveillance System

Contrast this with building security personnel who monitor activities within specific departments. Unlike border control, these internal agents possess contextual awareness—they know which office you're visiting, can access internal systems, and intervene during specific phases of your visit. Spring Handler Interceptors fulfill this role within the framework's ecosystem.

Interceptors leverage Spring's AOP capabilities and operate with in the DispatcherServlet's request handling workflow. They target specific handler methods rather than blanket-coverage of all traffic. Through the HandlerInterceptor interface, developers gain fine-grained control across three distinct lifecycle phases: pre-processing before controller execution, post-processing after business logic complesion but before view rendering, and final cleanup after the complete request cycle—including exception scenarios. Crucially, interceptors maintain full access to the Spring ApplicationContext, enabling dependency injection of services, repositories, or configuration properties.

@Component
public class PerformanceAuditInterceptor implements HandlerInterceptor {
    
    private static final String TIMER_KEY = "performance_timer";
    
    @Autowired
    private MetricsCollector metricsCollector;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
                             Object handler) {
        request.setAttribute(TIMER_KEY, System.nanoTime());
        return true;
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, 
                           Object handler, ModelAndView model) {
        // Modify model data or response headers after controller execution
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
                                Object handler, Exception ex) {
        Long startTime = (Long) request.getAttribute(TIMER_KEY);
        if (startTime != null) {
            long duration = System.nanoTime() - startTime;
            metricsCollector.recordLatency(request.getRequestURI(), duration);
        }
    }
}

Architectural Distinctions

The fundamental divergence lies in their operational scopes and runtime environments. Filters function as servlet container components, processing raw ServletRequest and ServletResponse objects at the protocol level. They remain unaware of Spring's handler mappings or controller methods. Conversely, interceptors exist as Spring-managed beans, operating on HttpServletRequest and HttpServletResponse with intimate knowledge of the target handler method via the Object handler parameter.

Filters accommodate universal concerns—encoding standardization, CORS handling, authentication gates, and payload compression. Interceptors address domain-specific cross-cutting concerns: method-level authorization, transactional metadata enrichment, view model manipulation, and precision timing metrics. While filters can redirect or rewrite requests through wrapper implementations, interceptors elegantly handle business context management through the ModelAndView object and exception handling hooks.

Implementation Contexts

Deploy filters when requiring coarse-grained network layer controls: SSL termination validation, request payload sanitization, or legacy integration points. Utilize interceptors for fine-grained MVC workflow orchestration: populating thread-local security contexts, enforcing method-level rate limiting, or implementing response enrichment strategies that require access to service-layer components.

In microservice architectures, filters often handle JWT signature verification at the edge, while interceptors manage tenant context propagation and database routing decisions within the service boundary. This layered approach ensures protocol-level security remains decoupled from business workflow orchestration.

Related Articles

Efficient Usage of HTTP Client in IntelliJ IDEA

IntelliJ IDEA incorporates a versatile HTTP client tool, enabling developres to interact with RESTful services and APIs effectively with in the editor. This functionality streamlines workflows, replac...

Installing CocoaPods on macOS Catalina (10.15) Using a User-Managed Ruby

System Ruby on macOS 10.15 frequently fails to build native gems required by CocoaPods (for example, ffi), leading to errors like: ERROR: Failed to build gem native extension checking for ffi.h... no...

Resolve PhpStorm "Interpreter is not specified or invalid" on WAMP (Windows)

Symptom PhpStorm displays: "Interpreter is not specified or invalid. Press ‘Fix’ to edit your project configuration." This occurs when the IDE cannot locate a valid PHP CLI executable or when the debu...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.