How are interceptors used in Spring MVC?

Interceptors in Spring MVC let you run custom logic before and after a controller handles a request, without modifying the controller itself. They implement the HandlerInterceptor interface and plug into the request lifecycle at three defined points.

Key Points: • preHandle runs before the controller method executes and can short-circuit the request by returning false, useful for authentication checks. • postHandle runs after the controller method returns but before the view is rendered, letting you modify the Model or add common attributes. • afterCompletion runs after the view has been rendered, typically used for cleanup or logging, and always runs even if an exception occurred. • Interceptors are registered globally or for specific path patterns through a WebMvcConfigurer, rather than annotated onto individual controllers. • Compared to servlet Filters, interceptors have access to the Spring handler and Model, since they run inside the Spring MVC layer rather than at the raw servlet level.

Example: A logging interceptor could record the start time in preHandle and log the total request duration in afterCompletion, giving per-request timing without adding that code to every controller method.

Code Example:

public class LoggingInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
        req.setAttribute("startTime", System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object handler, Exception ex) {
        long start = (long) req.getAttribute("startTime");
        System.out.println("Request took " + (System.currentTimeMillis() - start) + "ms");
    }
}

Interview Tip: A concise interview answer is:

"Interceptors implement HandlerInterceptor and hook into preHandle, postHandle, and afterCompletion around a controller's execution, which makes them a good fit for cross-cutting concerns like logging, authentication, and request timing. Unlike filters, they run inside the Spring MVC layer, so they have access to the handler and Model."