How to intercept Spring MVC requests

Sitewide-Feb4of4300x250 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:

@Component
public class RequestLogger extends HandlerInterceptorAdapter {
	
    private static Log log = LogFactory.getLog(RequestLogger.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
        log.info(request.getMethod() + " " + 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:

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private RequestLogger requestLogger;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(requestLogger);
    }
}

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.

Leave a Reply

Your email address will not be published. Required fields are marked *