Filters & Interceptors
Filter vs HandlerInterceptor — lifecycle differences, use cases, request/response manipulation
- Implement a Servlet Filter for cross-cutting concerns (logging, CORS)
- Write a HandlerInterceptor with preHandle/postHandle/afterCompletion
- Choose between Filter and Interceptor for a given requirement
Series:
Spring Boot Deep Dive | Topic: Filters vs Interceptors Level: Intermediate | Prerequisite: Spring MVC, @Controller, Dispatcher Servlet basics
Table of Contents
- Overview
- One-Line Definitions
- The Big Picture — Request Lifecycle
- What is a Servlet?
- What is the Dispatcher Servlet?
- Filters — Deep Dive
- Where Filters Live
- Filter Interface Methods
- Creating a Filter
- Registering a Filter with Order
- Filter Execution Order
- Where Interceptors Live
- Interceptor Interface Methods
- Creating an Interceptor
- Registering Multiple Interceptors with Order
- Interceptor Execution Order
- preHandle Returning False
- Combined Request Flow — Filters + Interceptors Together
- When to Use What
- Filters vs Interceptors — Comparison Table
- Mermaid Diagrams
- Key Observations
- Common Mistakes
- Best Practices
- Interview Notes
- Practice Questions
- Summary
Overview
When an HTTP request arrives at a Spring Boot application, it passes through several layers before reaching your controller method — and through several layers again on the way back. Two of the most important interception mechanisms along this path are Filters and Interceptors.
Both allow you to:
- Inspect and modify the incoming request
- Inspect and modify the outgoing response
- Execute logic before and after the core business code runs
But they sit at different positions in the request lifecycle, serve different scopes, and belong to different frameworks entirely. Knowing when to use each one is a frequently asked interview question and an important day-to-day architectural decision.
One-Line Definitions
Filter
— Intercepts HTTP requests and responses before they reach a Servlet.
Interceptor
— Intercepts HTTP requests and responses after the Servlet is chosen but before they reach the Controller (and after the Controller responds).
Keep these definitions in mind. They will make complete sense once you see the full request lifecycle.
Request Lifecycle
When an HTTP request enters a Spring Boot application, it travels through the following layers in order:
1HTTP Request2 ↓3Servlet Container (e.g. Tomcat)4 ↓5[ Filter Chain ] ← Filters live here6 ↓7Dispatcher Servlet ← Servlet chosen8 ↓9[ Interceptor Chain ] ← Interceptors live here10 ↓11Controller Method ← Your business logic12 ↓13[ Interceptors (post) ]14 ↓15[ Filters (post) ]16 ↓17HTTP ResponseThis single diagram explains the entire Filter vs Interceptor story:
- Filters sit between the Servlet Container and the Servlet
- Interceptors sit between the Dispatcher Servlet and the Controller
What is a Servlet?
Before understanding where Filters and Interceptors live, you must understand what a Servlet is.
Definition
A Servlet is a plain Java class that:
- Accepts an incoming HTTP request
- Processes it
- Returns an HTTP response
The Servlet Container (e.g., Tomcat, Jetty) manages all Servlets and routes incoming requests to the appropriate one.
Multiple Servlets in a Monolithic Application
In older monolithic applications, it was common to have multiple Servlets, each responsible for a different category of request:
| Servlet | Handles |
|---|---|
RestApiServlet | All REST API calls (/api/*) |
SoapServlet | All SOAP API calls |
FileUploadServlet | File upload endpoints |
StaticContentServlet | Images, CSS, JS files |
Each Servlet could declare which URL pattern it handles, and the Servlet Container would route requests accordingly.
Servlets in Microservices / Spring Boot
In modern Spring Boot microservices, the need for multiple Servlets has greatly reduced. Spring Boot provides a single, powerful Servlet called the Dispatcher Servlet that handles all requests (default pattern: /*).
Instead of writing business logic directly in the Servlet (as was done in older code with factory-style if/else routing), Spring Boot's Dispatcher Servlet delegates to Controllers — which is where your business logic lives today.
Dispatcher Servlet
The Dispatcher Servlet is Spring Boot's default Servlet. It:
- Handles all incoming HTTP requests (default pattern:
/*) - Determines which
@Controlleror@RestControllershould handle the request - Creates the appropriate handler and invokes it
- Manages the response back to the client
1Dispatcher Servlet responsibilities:21. Receive request from Servlet Container32. Consult Handler Mapping → find the right controller method43. Invoke Interceptors (preHandle)54. Call the Controller method65. Invoke Interceptors (postHandle)76. Render the response87. Invoke Interceptors (afterCompletion)/ — meaning it handles every incoming request. You can restrict this (e.g., to /api/) via configuration, but this is rarely needed in microservices.Filters
Where Filters Live
Filters live between the Servlet Container and the Servlet. This means they execute before the Servlet Container has even decided which Servlet will handle the request.
1HTTP Request → Servlet Container → [Filter 1 → Filter 2 → ...] → ServletBecause Filters execute before Servlet selection, they are:
- Framework-agnostic — they work regardless of whether the underlying framework is Spring, plain Java EE, Jakarta EE, etc.
- Servlet-agnostic — they apply to ALL servlets, not just the Dispatcher Servlet
- Scope: entire application — every request passes through every configured filter
Real-World Use Case Spring Security
Spring Security uses Filters, not Interceptors, because security must be applied to all HTTP requests regardless of the underlying servlet. It is generic, cross-cutting infrastructure that should not be tied to Spring MVC's Dispatcher Servlet.
Filter Interface Methods
The Filter interface (from jakarta.servlet or javax.servlet) defines three methods:
1public interface Filter {2 void init(FilterConfig filterConfig) throws ServletException;3 void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)4 throws IOException, ServletException;5 void destroy();6}| Method | When Called | Purpose |
|---|---|---|
init() | Once when the Filter object is created | Initialization logic — set up resources, read config |
doFilter() | On every matching request | Main processing logic — executed for each request |
destroy() | Once when the Filter is destroyed | Cleanup — release resources |
◆ `doFilter()` The Core Method
doFilter is the main method. It receives:
ServletRequest request— the incoming HTTP requestServletResponse response— the outgoing HTTP responseFilterChain chain— the remaining filters and the eventual servlet
1@Override2public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)3 throws IOException, ServletException {4
5 // ✅ Logic BEFORE passing to next filter/servlet6 System.out.println("MyFilter: Before processing");7
8 chain.doFilter(request, response); // ← Pass control to next filter or servlet9
10 // ✅ Logic AFTER the servlet/controller has processed11 System.out.println("MyFilter: After processing");12}chain.doFilter(request, response) passes control to the next Filter in the chain, or to the Servlet if no more Filters remain. If you do not call this, the request is terminated — no further filters, no servlet, no controller will be invoked.Creating a Filter
1import jakarta.servlet.Filter;2import jakarta.servlet.FilterChain;3import jakarta.servlet.FilterConfig;4import jakarta.servlet.ServletException;5import jakarta.servlet.ServletRequest;6import jakarta.servlet.ServletResponse;7import java.io.IOException;8
9public class MyFilter1 implements Filter {10
11 @Override12 public void init(FilterConfig filterConfig) throws ServletException {13 // Called once at startup. Initialize resources here if needed.14 System.out.println("MyFilter1: init");15 }16
17 @Override18 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)19 throws IOException, ServletException {20 System.out.println("MyFilter1: inside - before processing");21
22 chain.doFilter(request, response); // Continue to next filter or servlet23
24 System.out.println("MyFilter1: completed");25 }26
27 @Override28 public void destroy() {29 // Called once at shutdown. Clean up resources here.30 System.out.println("MyFilter1: destroy");31 }32}Registering a Filter with Order
Filters are registered as Spring beans using FilterRegistrationBean. The setOrder() method controls execution order — lower number = runs first.
1@Configuration2public class FilterConfig {3
4 @Bean5 public FilterRegistrationBean<MyFilter1> registerFilter1() {6 FilterRegistrationBean<MyFilter1> registration = new FilterRegistrationBean<>();7 registration.setFilter(new MyFilter1());8 registration.addUrlPatterns("/*"); // Apply to all URLs9 registration.setOrder(1); // Order 1 = runs first10 return registration;11 }12
13 @Bean14 public FilterRegistrationBean<MyFilter2> registerFilter2() {15 FilterRegistrationBean<MyFilter2> registration = new FilterRegistrationBean<>();16 registration.setFilter(new MyFilter2());17 registration.addUrlPatterns("/*");18 registration.setOrder(2); // Order 2 = runs second19 return registration;20 }21}MyFilter1 and MyFilter2 do not have @Component annotation here — because we are manually creating instances via new inside the FilterRegistrationBean. If you add @Component to the filter class, Spring will auto-register it, but you lose control over ordering unless you also implement Ordered or use @Order.Filter Execution Order
With two filters configured (Filter1 order=1, Filter2 order=2):
1Request → Filter1 (doFilter: before)2 → Filter2 (doFilter: before)3 → Dispatcher Servlet4 → Controller (business logic)5 ← Filter2 (doFilter: after chain.doFilter)6 ← Filter1 (doFilter: after chain.doFilter)7ResponseRequest path: Filter1 → Filter2 → Servlet → Controller Response path: Controller → Servlet → Filter2 → Filter1
The response travels back in reverse filter order — same as how a stack unwinds.
Interceptors
Where Interceptors Live
Interceptors live between the Dispatcher Servlet and the Controller. They execute after the Servlet Container has chosen the Dispatcher Servlet but before the Dispatcher Servlet routes to a specific Controller method.
1HTTP Request → Servlet Container → Filters → Dispatcher Servlet → [Interceptors] → ControllerBecause Interceptors execute inside the Dispatcher Servlet, they are:
- Spring MVC-specific — they are a Spring framework concept
- Dispatcher Servlet-specific — they only apply to requests handled by the Dispatcher Servlet
- Controller-aware — they have access to the handler method that will be invoked
- Application-specific — best for logic tied to your application's REST API layer
Interceptor Interface Methods
The HandlerInterceptor interface defines three methods:
1public interface HandlerInterceptor {2 boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)3 throws Exception;4
5 void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,6 ModelAndView modelAndView) throws Exception;7
8 void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,9 Exception ex) throws Exception;10}| Method | Return Type | When Called | Purpose |
|---|---|---|---|
preHandle() | boolean | Before controller method executes | Pre-processing — authentication, logging, validation |
postHandle() | void | After controller method executes, before response is sent | Post-processing — modify ModelAndView |
afterCompletion() | void | After complete request is finished (response sent) | Cleanup, resource release, final logging |
◆ `preHandle()` The Gate Keeper
preHandle is unique because it returns a boolean:
true→ proceed; pass the request to the next interceptor or controllerfalse→ stop; do NOT invoke the next interceptor or controller
1@Override2public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)3 throws Exception {4 System.out.println("Interceptor1: preHandle");5
6 // Example: check for auth token7 String token = request.getHeader("Authorization");8 if (token == null) {9 response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);10 return false; // ← Stop the chain; controller will NOT be called11 }12
13 return true; // ← Continue to next interceptor and then controller14}preHandle() returns false, Spring immediately stops the interceptor chain. No further preHandle() calls, no controller invocation, no postHandle() calls. However, afterCompletion() IS called for all interceptors whose preHandle() already returned true.Creating an Interceptor
1import jakarta.servlet.http.HttpServletRequest;2import jakarta.servlet.http.HttpServletResponse;3import org.springframework.stereotype.Component;4import org.springframework.web.servlet.HandlerInterceptor;5import org.springframework.web.servlet.ModelAndView;6
7@Component8public class MyCustomInterceptor1 implements HandlerInterceptor {9
10 @Override11 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)12 throws Exception {13 System.out.println("Interceptor1: preHandle");14 return true; // Continue processing15 }16
17 @Override18 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,19 ModelAndView modelAndView) throws Exception {20 System.out.println("Interceptor1: postHandle");21 }22
23 @Override24 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,25 Exception ex) throws Exception {26 System.out.println("Interceptor1: afterCompletion");27 }28}Registering Multiple Interceptors with Order
Interceptors are registered by implementing WebMvcConfigurer and overriding addInterceptors(). The order in which you add them determines their execution order:
1import org.springframework.beans.factory.annotation.Autowired;2import org.springframework.context.annotation.Configuration;3import org.springframework.web.servlet.config.annotation.InterceptorRegistry;4import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;5
6@Configuration7public class InterceptorConfig implements WebMvcConfigurer {8
9 @Autowired10 private MyCustomInterceptor1 interceptor1;11
12 @Autowired13 private MyCustomInterceptor2 interceptor2;14
15 @Override16 public void addInterceptors(InterceptorRegistry registry) {17 registry.addInterceptor(interceptor1); // Added first → runs first on request18 registry.addInterceptor(interceptor2); // Added second → runs second on request19 }20}Interceptor Execution Order
With two interceptors (Interceptor1 added first, Interceptor2 added second):
1Request → Interceptor1.preHandle()2 → Interceptor2.preHandle()3 → Controller (business logic runs)4 ← Interceptor2.postHandle()5 ← Interceptor1.postHandle()6 ← Interceptor2.afterCompletion()7 ← Interceptor1.afterCompletion()8ResponseRequest path (preHandle): Interceptor1 → Interceptor2 → Controller Response path (postHandle + afterCompletion): Interceptor2 → Interceptor1
Again, the response unwinds in reverse order — mirror image of the request path.
preHandle Returning False
1Request → Interceptor1.preHandle() → returns true ✓2 → Interceptor2.preHandle() → returns false ✗3 ✗ Controller is NOT invoked4 ✗ postHandle is NOT called for any interceptor5 ✓ Interceptor1.afterCompletion() IS called (its preHandle returned true)6 ✗ Interceptor2.afterCompletion() is NOT called (its own preHandle returned false)7Response (sent directly with whatever Interceptor2 wrote to response, e.g., 401)Combined Flow Filters + Interceptors Together
When both Filters and Interceptors are configured, the full request/response lifecycle looks like this:
Request Path (Incoming)
1HTTP Request2 ↓3Servlet Container (Tomcat)4 ↓5Filter1.doFilter() [before chain.doFilter()]6 ↓7Filter2.doFilter() [before chain.doFilter()]8 ↓9Dispatcher Servlet10 ↓11Interceptor1.preHandle()12 ↓13Interceptor2.preHandle()14 ↓15Controller Method (business logic)Response Path (Outgoing)
1Controller Method returns2 ↓3Interceptor2.postHandle()4 ↓5Interceptor1.postHandle()6 ↓7Interceptor2.afterCompletion()8 ↓9Interceptor1.afterCompletion()10 ↓11Filter2.doFilter() [after chain.doFilter()]12 ↓13Filter1.doFilter() [after chain.doFilter()]14 ↓15HTTP Response sent to clientFull Console Output (Both Filters + Both Interceptors)
1Filter1: inside - before processing2Filter2: inside - before processing3Interceptor1: preHandle4Interceptor2: preHandle5[Controller executes: hitting business logic]6Interceptor2: postHandle7Interceptor1: postHandle8Interceptor2: afterCompletion9Interceptor1: afterCompletion10Filter2: completed11Filter1: completedWhen to Use What
| Scenario | Use |
|---|---|
| Authentication / Authorization for all requests | Filter (Spring Security uses filters) |
| CORS headers on all responses | Filter |
| Request/Response logging for all endpoints | Filter |
| Request body compression / decompression | Filter |
| Rate limiting at the infrastructure level | Filter |
| Logging specific to your REST API layer | Interceptor |
| Checking custom headers before controller | Interceptor |
| Measuring controller execution time | Interceptor |
| Role-based access to specific API endpoints | Interceptor |
| Modifying ModelAndView before rendering | Interceptor (postHandle) |
| Cleanup after a specific controller completes | Interceptor (afterCompletion) |
The Decision Rule
1Is the logic generic and applicable to ALL servlets (not just Spring MVC)?2 YES → Use a Filter3 NO → Is the logic specific to Spring MVC / your REST controllers?4 YES → Use an InterceptorFilters vs Interceptors Comparison Table
| Feature | Filter | Interceptor |
|---|---|---|
| Specification | Java Servlet Specification (jakarta.servlet) | Spring Framework (HandlerInterceptor) |
| Position in lifecycle | Before Servlet | After Servlet, before Controller |
| Scope | All Servlets | Specific Servlet (Dispatcher Servlet) |
| Framework dependency | Framework-agnostic (works without Spring) | Spring MVC specific |
| Access to Spring context | ❌ Limited — not a Spring bean by default | ✅ Full Spring context access |
| Access to handler info | ❌ No | ✅ Yes — knows which controller method will run |
| Main interface | jakarta.servlet.Filter | HandlerInterceptor |
| Key method | doFilter() | preHandle(), postHandle(), afterCompletion() |
| Stop the chain | Do not call chain.doFilter() | Return false from preHandle() |
| Ordering | FilterRegistrationBean.setOrder(n) | Order of addInterceptor() calls |
| Real-world use | Spring Security, CORS, compression, logging | Auth checks, API logging, execution timing |
Mermaid Diagrams
Full Request Lifecycle
Filter vs Interceptor Position
Interceptor preHandle Chain False Return
When to Choose Filter vs Interceptor
Servlet Architecture Monolithic vs Microservice
Key Observations
- Filters are part of the Java Servlet specification — they work with any Java web framework (Spring, Jakarta EE, plain servlets). Interceptors are Spring MVC specific.
- Filters execute before the Servlet Container decides which servlet to use — they are truly framework-agnostic at the point they execute.
- Interceptors execute inside the Dispatcher Servlet — they are Spring's way of adding pre/post logic around controller invocations.
- Both can modify request and response — the choice between them is not about capability but about the appropriate position in the lifecycle and the scope of the concern being addressed.
preHandle()returningfalseis a hard stop — no controller, no subsequentpreHandlecalls. It is the correct way to reject a request at the interceptor level (e.g., return 401 Unauthorized).
chain.doFilter()not being called in a Filter is a hard stop — equivalent topreHandlereturningfalse.
- Response path is always the reverse of the request path — both for filters and interceptors. This is the "stack unwind" pattern — last in, first out.
- Spring Security is entirely built on Filters — it creates a chain of security filters (
SecurityFilterChain) that sits in the Filter layer, completely before Spring MVC. This is by design so that security applies to all HTTP traffic.
- Interceptors have access to the handler object — they know which controller method will be called, which Filters do not. This allows interceptors to read controller-level annotations for fine-grained logic.
- You can have multiple Filters and multiple Interceptors — both support ordering to control execution sequence.
Common Mistakes
Mistake 1 Using Interceptor for Global Security
1// ❌ Wrong — Interceptors only cover the Dispatcher Servlet2// If you have other servlets, they won't be protected3@Component4public class SecurityInterceptor implements HandlerInterceptor {5 @Override6 public boolean preHandle(...) {7 // This only intercepts requests going to Spring MVC controllers8 // Requests to other servlets bypass this entirely9 }10}11
12// ✅ Correct — Spring Security uses Filters for global coverage13// Spring Security's FilterChain covers all HTTP trafficMistake 2 Forgetting to Call `chain.doFilter()`
1// ❌ Wrong — request terminates here, controller never runs2@Override3public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)4 throws IOException, ServletException {5 System.out.println("Before");6 // Missing chain.doFilter(req, res) !7 System.out.println("After");8}9
10// ✅ Correct11@Override12public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)13 throws IOException, ServletException {14 System.out.println("Before");15 chain.doFilter(req, res); // Must call this to continue16 System.out.println("After");17}Mistake 3 Confusing Interceptor Ordering with Filter Ordering
Filters use FilterRegistrationBean.setOrder(n) — lower number runs first. Interceptors use the order they are added to the InterceptorRegistry — first added runs first.
1// ✅ Filter ordering — explicit numeric order2registration1.setOrder(1); // runs first3registration2.setOrder(2); // runs second4
5// ✅ Interceptor ordering — positional order in addInterceptors6registry.addInterceptor(interceptor1); // runs first7registry.addInterceptor(interceptor2); // runs secondMistake 4 Expecting `postHandle` to Run When `preHandle` Returns False
If any preHandle returns false, postHandle is not called for any interceptor. Only afterCompletion is called for interceptors whose preHandle already returned true.
Best Practices
- Use Filters for cross-cutting infrastructure concerns — authentication tokens, CORS, request/response logging at the HTTP level, compression.
- Use Interceptors for application-layer concerns — validating business-specific headers, logging at the API level, measuring controller execution time.
- Keep Filters lean — since they run for every request before any Spring processing, expensive logic here impacts all traffic.
- Use
preHandlefor early rejection — it is the cleanest point to reject unauthorized or invalid requests before any business logic runs.
- Use
afterCompletionfor cleanup — it always runs (even when exceptions occur), making it ideal for releasing resources, closing connections, or final audit logging.
- Name your filters and interceptors clearly —
AuthenticationFilter,CorrelationIdInterceptor,ExecutionTimingInterceptor. The name should state the purpose.
- Prefer Spring Security for authentication/authorization — do not implement security from scratch using custom Filters or Interceptors unless you have a very specific reason.
- Be explicit about URL patterns — when registering filters with
FilterRegistrationBean, always specifyaddUrlPatterns(). A filter that applies to everything when it only needs to apply to/api/*wastes CPU cycles.
Interview Notes
Commonly Asked Questions
Q: What is the difference between a Filter and an Interceptor? A: A Filter intercepts HTTP requests before they reach a Servlet — it is part of the Java Servlet spec and applies to all servlets. An Interceptor is Spring MVC-specific and intercepts requests after the Dispatcher Servlet is chosen but before the Controller is invoked. Filters are framework-agnostic; Interceptors are Spring-specific.
Q: Where does a Filter sit in the request lifecycle? A: Between the Servlet Container (e.g., Tomcat) and the Servlet (e.g., Dispatcher Servlet).
Q: Where does an Interceptor sit in the request lifecycle? A: Between the Dispatcher Servlet and the Controller.
Q: Why does Spring Security use Filters and not Interceptors? A: Spring Security needs to secure all HTTP traffic, regardless of which servlet handles it. Interceptors only apply to requests going through the Dispatcher Servlet. By using Filters, Spring Security can intercept every request at the servlet container level, before any framework-specific processing.
Q: What happens if preHandle() returns false? A: The entire chain stops. No further preHandle() calls, no controller invocation, no postHandle() calls. afterCompletion() is called only for interceptors whose preHandle() already returned true.
Q: Can you modify the request/response in both Filters and Interceptors? A: Yes, both have access to the HttpServletRequest and HttpServletResponse objects and can read/modify headers, body (using wrapper classes), etc. The choice is about scope and position, not capability.
Q: What is the execution order when you have 2 Filters and 2 Interceptors? A: Request: Filter1 → Filter2 → Interceptor1.preHandle → Interceptor2.preHandle → Controller. Response: Interceptor2.postHandle → Interceptor1.postHandle → Interceptor2.afterCompletion → Interceptor1.afterCompletion → Filter2 → Filter1.
Q: How do you control the order of Filters? Of Interceptors? A: Filters — use FilterRegistrationBean.setOrder(n), lower number runs first. Interceptors — the order they are added via registry.addInterceptor() in WebMvcConfigurer.addInterceptors().
Q: Can an Interceptor access which controller method is going to handle the request? A: Yes — the handler parameter in preHandle(request, response, handler) is typically a HandlerMethod object that exposes the controller class and method, including their annotations.
Practice Questions
Easy
- What is the Java interface you implement to create a Filter?
- What is the Spring interface you implement to create an Interceptor?
- In what order do Filters execute on the response — same as request or reversed?
- What does
chain.doFilter()do? What happens if you don't call it?
Medium
- You need to add a
X-Correlation-IDheader to every request for distributed tracing. Should you use a Filter or Interceptor? Why? - You need to check that a user has the
ADMINrole before certain controller methods execute. Should you use a Filter or Interceptor? What are the trade-offs? - Explain the method execution order for
preHandle,postHandle, andafterCompletionwhen two interceptors are registered and the second interceptor'spreHandlereturnsfalse. - Write a Filter that logs the HTTP method, URL, and response status code for every request.
Hard
- You have a Spring Boot application with both a Dispatcher Servlet (
/) and a customFileUploadServlet(/upload/). You register an Interceptor for your application. Will it intercept requests to/upload/*? Why or why not? How would you intercept those requests? - Describe in detail the full lifecycle of an HTTP
GET /api/usersrequest through a Spring Boot application that has: 2 Filters, 2 Interceptors, and a@RestController. Include both request and response paths. - A developer wants to implement request throttling (rate limiting) and puts it in an Interceptor. A security review flags this as incorrect placement. What is the reviewer's concern and what is the correct solution?
- How does Spring Security's
SecurityFilterChainrelate to the Filter concept discussed in this guide? Why is it implemented as a Filter chain rather than an Interceptor chain?
Summary
| Concept | Key Point |
|---|---|
| Filter | Java Servlet Specification; sits before the Servlet; applies to all servlets |
| Interceptor | Spring MVC specific; sits between Dispatcher Servlet and Controller |
| Servlet | Java class that processes HTTP requests and returns responses |
| Dispatcher Servlet | Spring Boot's default servlet; routes all requests to Controllers |
| Filter interface | jakarta.servlet.Filter → init(), doFilter(), destroy() |
| Interceptor interface | HandlerInterceptor → preHandle(), postHandle(), afterCompletion() |
chain.doFilter() | Passes control to next Filter or Servlet; must be called to continue |
preHandle() returns false | Hard stop; no controller, no postHandle; afterCompletion runs for already-true interceptors |
| Request order | Filter1 → Filter2 → Interceptor1 → Interceptor2 → Controller |
| Response order | Controller → Interceptor2 → Interceptor1 → Filter2 → Filter1 |
| Filter ordering | FilterRegistrationBean.setOrder(n) — lower number first |
| Interceptor ordering | Order of registry.addInterceptor() calls |
| Use Filters for | Security, CORS, compression, global logging — framework-agnostic concerns |
| Use Interceptors for | Application-layer logging, auth header checks, execution timing — Spring MVC concerns |
| Spring Security uses | Filters — because security must apply before any servlet, not just Dispatcher Servlet |
End of Filters vs Interceptors Study Guide
Mastery check
How well can you recall this?
Finished this lesson?