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

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.

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.

Last updated: 16 July 2026

Previous question: What are the advantages of using a ContentNegotiatingViewResolver?

Next question: What are the methods in the HandlerInterceptor interface?

More Spring MVC (Optional) interview questions

All Spring MVC (Optional) questions