InterviewVault
Welcome back, Sujit Kumar Mishra
Admin
SK Mishra
Revision Mode
Document technical questions and best-practice answers.
What kind of interceptors you have used in Spring to intercept the request and response details of a controller endpoint?
In Spring, to intercept the request and response details of a controller endpoint, we commonly use two main types of interceptors:
1: HandlerInterceptor
- This is an interface provided by Spring MVC.
- We can create our own class by implementing HandlerInterceptor and override methods like:
preHandle()– runs before the controller method.postHandle()– runs after the controller method but before the response is sent.afterCompletion()– runs after the complete request is finished.
- This is useful for logging, authentication, or modifying requests/responses.
2: Filter
- This is a standard Servlet feature, but Spring Boot supports it easily.
- We can create a class that implements javax.servlet.Filter.
- The doFilter() method lets us intercept both the request and response before they reach the controller and after the response leaves the controller.
In summary:
1: Use HandlerInterceptor for Spring-specific interception.
2: Use Filter for more general or lower-level interception.
Both can be used to log, check, or modify request and response details in a Spring application.