HandlerInterceptor in Spring MVC — Pre and Post Processing
Fast recall
Quick revision
Core answer
Knowledge of Spring MVC's interceptor mechanism for cross-cutting concerns and how it differs from servlet filters
Confusing Spring HandlerInterceptor with Servlet Filter — both intercept requests but at different layers with different capabilities
Explain the three methods: preHandle runs before controller, postHandle runs after controller but before response, afterCompletion runs after response is sent
Interview-ready guide
Interview answer
An interceptor can record a start time in preHandle and attach handler information to a timing metric in afterCompletion. Returning false from preHandle stops handler execution, but the interceptor must then complete the response if needed. Filters are a better fit for compression, raw request wrapping, and concerns that apply outside MVC. Rate limiting and security may require filters or dedicated infrastructure depending on where the protection must run.
HandlerInterceptor in Spring MVC — Pre and Post Processing
Direct Answer
A HandlerInterceptor runs around Spring MVC handler execution. preHandle runs before the handler, postHandle after a successful handler invocation but before view completion, and afterCompletion after request completion. It is not simply Spring's equivalent of a servlet Filter: filters operate at the servlet-container level and can wrap request/response bodies, while interceptors know the selected handler.
Code Example
@Component
public class RequestTimingInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
var startTime = System.currentTimeMillis();
request.setAttribute("startTime", startTime); // Store for later
return true; // Continue to controller; return false to short-circuit
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
// Controller method executed successfully, but response not sent yet
// Can modify ModelAndView here for traditional MVC apps
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
var startTime = (Long) request.getAttribute("startTime");
var duration = System.currentTimeMillis() - startTime;
System.out.printf("[%s %s] completed in %d ms%n", request.getMethod(), request.getRequestURI(), duration);
// Runs even if controller throws exception
}
}
@Configuration
class WebConfig implements WebMvcConfigurer {
@Autowired private RequestTimingInterceptor timingInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(timingInterceptor).addPathPatterns("/api/**");
}
}
Common Mistakes & Pitfalls
- Confusing with Servlet Filters: Freshers hear "intercepts requests" and think it's the same as Filter. But HandlerInterceptor runs after DispatcherServlet resolves the handler — so it has access to the controller method and Spring context. Filters run before DispatcherServlet even sees the request.
- Returning false in preHandle without setting response: If preHandle returns false, Spring short-circuits — the controller doesn't run. Freshers forget to write an error response, so the client gets an empty 200 OK.
- Assuming postHandle runs on exception: If the controller throws an exception, postHandle is skipped. Only afterCompletion runs, and it receives the exception as a parameter.
- Not registering the interceptor: Writing a HandlerInterceptor class but forgetting to add it to InterceptorRegistry means it never runs — freshers wonder why their logging doesn't work.
Check your understanding
Answer these without looking back at the article.
- What is the difference between HandlerInterceptor and Servlet Filter?
- How do you register a HandlerInterceptor in Spring Boot?
- What does preHandle returning false do?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.