HandlerInterceptor defines three lifecycle hook methods that let you run custom logic at different points around a controller method's execution within the DispatcherServlet request cycle.
Key Points: • preHandle() runs before the handler method executes and returning false stops processing right there, useful for auth checks. • postHandle() runs after the handler executes but before the view is rendered, giving a chance to modify the ModelAndView. • afterCompletion() runs after the view has been rendered, making it the right place for logging or resource cleanup, and it still runs even if an exception occurred. • All three methods are optional to override since HandlerInterceptor provides default no-op implementations (or you can extend HandlerInterceptorAdapter in older Spring versions). • Interceptors are registered through a WebMvcConfigurer's addInterceptors method, optionally scoped to specific URL patterns.
Example: A logging interceptor might record the start time in preHandle(), then in afterCompletion() compute and log the total request duration, giving per-request timing without touching any controller code.
Code Example:
public class LoggingInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
req.setAttribute("startTime", System.currentTimeMillis());
return true;
}
public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object handler, Exception ex) {
long duration = System.currentTimeMillis() - (long) req.getAttribute("startTime");
System.out.println("Request took " + duration + "ms");
}
}Interview Tip: A concise interview answer is:
"HandlerInterceptor has three hooks: preHandle before the controller runs, where returning false short-circuits the request; postHandle after the controller but before the view renders, for tweaking the model; and afterCompletion after rendering, for cleanup or logging, which fires even on exceptions."