Sometimes we may need to intercept the requests received by our Spring MVC application. For example, we may be running a paid service and like to count the requests per user.

Spring MVC handler-interceptors come in handy in such cases. Using handler interceptors, you can execute custom code before/after a controller method is executed, and/or after the complete request is finished. Spring documentation covers it very well – so, instead of talking theory, let’s quickly see how to code an interceptor for logging all requests.

All interceptors should either implement HandlerInterceptor or one of its sub-interfaces. Spring also provides a few convenient abstract classes, e.g. HandlerInterceptorAdapter, that our interceptor can just inherit.

So, let’s code a RequestLogger class extending HandlerInterceptorAdapter, as below:

public class RequestLogger extends HandlerInterceptorAdapter {
    private static Log log = LogFactory.getLog(RequestLogger.class);
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception { + " " + request.getServletPath() + " received");
        return true;

Next, we need to tell Spring MVC to use the interceptor. For that, we can configure a WebMvcConfigurerAdapter, as below:

public class MvcConfig extends WebMvcConfigurerAdapter {
    private RequestLogger requestLogger;
    public void addInterceptors(InterceptorRegistry registry) {

That’s all! If you now run your application and visit /, you’ll see a log line “GET / received.” Here is a complete Spring Boot demo application.