Spring MVC Interceptors Interview Questions and Answers
Master Spring MVC Interceptors with interview questions covering HandlerInterceptor, preHandle(), postHandle(), afterCompletion(), interceptor lifecycle, registration, authentication, logging, auditing, and production best practices.
Introduction
Enterprise applications often need to execute common logic before or after every request.
Examples include
- Authentication
- Authorization
- Request Logging
- Audit Logging
- Performance Monitoring
- API Rate Limiting
- Correlation IDs
- Metrics Collection
Instead of writing the same code inside every controller, Spring MVC provides Interceptors.
Interceptors execute around controller methods and allow centralized request processing.
Spring MVC Interceptor Architecture
flowchart LR
Client --> DispatcherServlet
DispatcherServlet --> Interceptor
Interceptor --> Controller
Controller --> Service
Service --> Database
Database --> Response
Response --> Interceptor
Interceptor --> Client
Q1. What is an Interceptor in Spring MVC?
Answer
An Interceptor is a Spring MVC component that executes before and after controller execution.
Typical use cases
- Authentication
- Authorization
- Logging
- Auditing
- Metrics
- Request tracing
Interceptors are executed by the DispatcherServlet.
Q2. What is HandlerInterceptor?
HandlerInterceptor is the primary Spring MVC interceptor interface.
It provides three lifecycle methods.
preHandle()
postHandle()
afterCompletion()
Applications implement this interface to intercept requests.
Q3. What is preHandle()?
preHandle() executes before the controller method.
Responsibilities
- Authentication
- Authorization
- Logging
- Validate headers
- Block requests
Example
public boolean preHandle(){
return true;
}
Return
true→ Continue requestfalse→ Stop processing
Q4. What is postHandle()?
postHandle() executes after controller execution but before the response is rendered.
Typical use cases
- Add model attributes
- Logging
- Modify response model
- Metrics collection
Interceptor Flow
sequenceDiagram
Client->>Interceptor: preHandle()
Interceptor->>Controller: Execute
Controller-->>Interceptor: postHandle()
Interceptor-->>Client: Response
Q5. What is afterCompletion()?
afterCompletion() executes after the complete request finishes.
Even if an exception occurs,
afterCompletion() still executes.
Typical use cases
- Cleanup
- Close resources
- Final logging
- Execution time calculation
Q6. How do you register an Interceptor?
Implement WebMvcConfigurer.
Example
@Configuration
public class WebConfig
implements WebMvcConfigurer{
}
Override
addInterceptors()
Spring automatically registers the interceptor.
Q7. Interceptor vs Filter
| Filter | Interceptor |
|---|---|
| Servlet API | Spring MVC |
| Executes before DispatcherServlet | Executes after DispatcherServlet |
| Works for all requests | Only controller requests |
| Container-managed | Spring-managed |
| Suitable for compression, CORS | Suitable for authentication, logging |
Both are frequently used together.
Q8. Can multiple Interceptors be used?
Yes.
Spring executes them in order.
Example
Logging
↓
Authentication
↓
Authorization
↓
Controller
Execution order is configurable.
Multiple Interceptors
flowchart TD
LoggingInterceptor --> AuthInterceptor
AuthInterceptor --> AuditInterceptor
AuditInterceptor --> Controller
Q9. What are common production use cases?
Common enterprise interceptors
- JWT Authentication
- Request Logging
- API Metrics
- Correlation IDs
- Audit Logging
- Localization
- Request Timing
These avoid duplication across controllers.
Q10. Interceptor Best Practices
Keep Logic Lightweight
Avoid heavy processing.
Avoid Business Logic
Use services instead.
Log Correlation IDs
Support distributed tracing.
Keep Authentication Centralized
Don't repeat in controllers.
Use Interceptors for Cross-Cutting Concerns
Avoid controller duplication.
Banking Example
flowchart TD
MobileApp --> DispatcherServlet
DispatcherServlet --> JWTInterceptor
JWTInterceptor --> AuditInterceptor
AuditInterceptor --> PaymentController
PaymentController --> PaymentService
PaymentService --> PostgreSQL
PaymentService --> JSONResponse
JSONResponse --> MobileApp
JWT validation and auditing occur before business processing.
Common Interview Questions
- What is an Interceptor?
- What is HandlerInterceptor?
- Explain
preHandle(). - Explain
postHandle(). - Explain
afterCompletion(). - How do you register an Interceptor?
- Interceptor vs Filter?
- Multiple Interceptors?
- Production use cases?
- Interceptor best practices?
Quick Revision
| Topic | Summary |
|---|---|
| Interceptor | Cross-cutting request processing |
| HandlerInterceptor | Spring MVC interceptor interface |
| preHandle() | Before controller |
| postHandle() | After controller, before response |
| afterCompletion() | After response completion |
| WebMvcConfigurer | Register interceptors |
| Logging | Common use case |
| Authentication | Common use case |
| Auditing | Common use case |
| Metrics | Performance monitoring |
Complete Interceptor Lifecycle
sequenceDiagram
Client->>DispatcherServlet: HTTP Request
DispatcherServlet->>Interceptor: preHandle()
Interceptor-->>DispatcherServlet: Continue
DispatcherServlet->>Controller: Execute
Controller->>Service: Business Logic
Service-->>Controller: Result
Controller-->>DispatcherServlet: Return
DispatcherServlet->>Interceptor: postHandle()
DispatcherServlet-->>Client: HTTP Response
DispatcherServlet->>Interceptor: afterCompletion()
Production Example – Banking Payment API
A banking platform exposes
POST /api/v1/payments
Requirements
- Authenticate JWT token.
- Generate correlation ID.
- Record request duration.
- Write audit logs.
- Capture exceptions.
Workflow
- Client sends a payment request.
JWTInterceptor.preHandle()validates the access token.- A correlation ID is added to the logging context (MDC).
- Controller processes the payment.
postHandle()records business metrics.- HTTP response is returned.
afterCompletion()logs execution time and clears MDC.
public class JwtInterceptor
implements HandlerInterceptor {
@Override
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler) {
// Validate JWT
return true;
}
}
flowchart LR
MobileApp --> DispatcherServlet
DispatcherServlet --> JwtInterceptor
JwtInterceptor --> CorrelationInterceptor
CorrelationInterceptor --> PaymentController
PaymentController --> PaymentService
PaymentService --> PostgreSQL
PaymentService --> PaymentResponse
PaymentResponse --> MobileApp
Filter vs Interceptor vs ControllerAdvice
| Feature | Filter | Interceptor | ControllerAdvice |
|---|---|---|---|
| Layer | Servlet Container | Spring MVC | Spring MVC |
| Runs Before DispatcherServlet | ✅ | ❌ | ❌ |
| Runs Before Controller | ✅ | ✅ | ❌ |
| Runs After Controller | ❌ | ✅ | ❌ |
| Handles Exceptions | Limited | Limited | ✅ |
| Typical Usage | CORS, Compression, Encoding | Authentication, Logging, Auditing | Global Exception Handling |
Interceptor Execution Order
flowchart TD
HTTPRequest --> Filter
Filter --> DispatcherServlet
DispatcherServlet --> InterceptorPreHandle
InterceptorPreHandle --> Controller
Controller --> InterceptorPostHandle
InterceptorPostHandle --> ViewRendering
ViewRendering --> InterceptorAfterCompletion
InterceptorAfterCompletion --> HTTPResponse
Key Takeaways
- Interceptors provide centralized processing for requests before and after controller execution.
- HandlerInterceptor defines three lifecycle methods:
preHandle(),postHandle(), andafterCompletion(). preHandle()is commonly used for authentication, authorization, logging, and request validation.postHandle()executes after the controller but before the response is rendered, making it useful for metrics and model enrichment.afterCompletion()always executes after request completion, making it ideal for cleanup, execution time logging, and resource release.- Interceptors are registered through WebMvcConfigurer and apply only to Spring MVC controller requests.
- Filters, Interceptors, and
@ControllerAdviceserve different purposes and are often used together in enterprise applications. - Interceptors are best suited for cross-cutting concerns, helping keep controllers clean, reusable, and maintainable.