Spring: Interceptors run around handlers, filters around everything

A filter is servlet-level and sees every request; an interceptor is Spring MVC-level and knows the handler.

Code
@Component
class TimingInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
        req.setAttribute("start", System.nanoTime());
        return true;    // false stops the request here
    }
    public void afterCompletion(HttpServletRequest req, HttpServletResponse res,
                                Object handler, Exception ex) {
        long ms = (System.nanoTime() - (long) req.getAttribute("start")) / 1_000_000;
        log.info("{} took {}ms", handler, ms);
    }
}
Output
OrderController#byId took 12ms
A filter would run even for static resources and 404s; an interceptor would not.
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-11