Learn how to create a logger interceptor using Spring.
Spring Interceptors has the ability to pre-handle and post-handle the web requests. Each interceptor class should extend the HandlerInterceptorAdapter class. Here we will create a Logger Interceptor by extending the HandlerInterceptorAdapter class. You can override any of the three callback methods preHandle(), postHandle() and afterCompletion(). As the names indicate the preHandle() method will be called before handling the request, the postHandle() method will be called after handling the request and the afterCompletion() method will be called after rendering the view.
In each method we will log information using log4j. First instantiate the logger in the static context, then set up the basic configuration so that the log messages will be logged on the console.
Now the logger interceptor is created you need to associate this interceptor with the handler mapping. Here we use BeanNameUrlHandlerMapping, incase you are using more than one handler mapping you need to associate the interceptor with each one of them. The code below shows how to associate an interceptor with the handler mapping.