How to intercept Spring MVC requests

Sitewide-10usd300x250 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;

One thought on “How to intercept Spring MVC requests

Leave a Reply

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