Spring MVC Interceptor example

In this article we will create a simple Spring MVC Interceptor example.

Spring MVC Interceptor

As the name suggests, Spring MVC Interceptors are java classes that are used to intercept any requests. Interceptors are configurable and can be configured on all the requests OR a group of requests. We can configure multiple requests based on our requirements. While configuring a interceptors we have exclude some of the requests that need not go through the interceptors.

Use of Interceptor

Interceptors are generally used for authorization of requests, common loggins done before and after a request is processed.

How to create a Spring MVC Interceptor

In spring, Interceptors are java class that either implement HandlerInterceptor or extend HandlerInterceptorAdaptor

HandlerInterceptorAdaptor is a spring class that allows the its sub class to only override the below three required methods from the HandlerInterceptor interface.
Extending HandlerInterceptorAdaptor is more convenient than implementing the HandlerInterceptor interface, as the HandlerInterceptorAdaptor has already implemented the interface methods and we need to only override the methods we need to add logic to.

3 important methods that we need to understand about the interceptors are
preHandle(..)
This method returns a boolean value. It is called just before the controller call. You can use this method to break or continue the processing of the execution chain.
If the method returns true, the handler execution chain will continue i.e. the controller will be called.
If the method returns false, the DispatcherServlet assumes the interceptor itself has taken care of requests and does not continue executing.
postHandle(..)
This method is called just after the controller call. You can use this method to add extra objects/attributes to Model object that will be send as a response.
afterCompletion(..)
This method is called after complete request is finished.

If there are multiple interceptors configured, preHandle() method is executed in the order of configuration whereas postHandle() and afterCompletion() methods are executed in the reverse order.

Now lets create a Spring MVC Interceptor Example.
In the attached example i have create 2 controller, home and employee. We will create a interceptor to log details when a request comes in. We will configure the interceptor to allow requests coming to HomeController to intercepted , but not to the EmployeedController.

Create Interceptor

Configure the Interceptor in dispatcher servlet

Output

When you access the below URL you will see output at the console
http://localhost:8080/interceptorexample/home

Spring MVC Interceptor Example for Beginners

and when you use the employee url no output will be logged as no interceptor will be called
http://localhost:8080/interceptorexample/employee

Download the Source – SpringMVC-Interceptor.zip