Interceptors are a very useful tool for controlling the flow. Thanks to them we can perform operations before every call, after it, but before the rendering of the view or at the end. Where can it come from? From performance monitoring (we count the time from the call to the end of the whole operation) to something like filters – eg, limiting access to selected subpages from indicated IP addresses.

We start by adding a class that implements the HandlerInterceptor interface (org.springframework.web.servlet.HandlerInterceptor).

We will need to implement three methods required by this interface.

PreHandle – is called before the controller serving the requested request. This method returns true or false, and depending on what it returns – the request is passed to the controller or not. If true returns, the controller will take further request handling. And that is where we could restrict access to selected addresses from some selected address pool.

PostHandle – is called after the controller has started, but before rendering the view. It also allows you to manipulate model data before displaying the view. This may be the place where we limit the displayed data depending on what logged-in user requests them.

After completion – called at last, after rendering and displaying the view. This method could be used to calculate the time of processing the entire request.

Instead of implementing the HandlerInterceptor interface, you can inherit the HandlerInterceptorAdapter class and override only the selected methods. How do you like, how comfortable?

In this first example, I limit myself to displaying the relevant messages in each method, which will allow us to observe the order of the operations performed.

I also add a regular controller to a method that handles the HTTP:

File content ***** – The servlet has been enriched with a fragment of <mvc: interceptors> tags:

This works in such a way that each time a Dispatcher processes the list of interceptors, it invokes the appropriate interceptors for each of them. You can between <mvc: interceptors> tags and

</ mvc: interceptors> insert consecutive beans with references to classes that implement HandlerInterceptor interfaces or inherit HandlersInterceptorAdapter and all of them will be called.

I am calling an address serviced by our controller:

One of the first thoughts that came to my mind after learning about this mechanism – is it possible to limit the operation of interceptors only to selected addresses? For example, some carefully guarded part of the application? In the configuration of this interceptor, we do not set it, but it is relatively easy to implement it ourselves, using the fact that in the interceptor we have access to the HttpServlerRequest object of our request.

The sample code would look like this:

if (request.getRequestURI.endsWith (“page”)) {

response.sendRedirect ( “”);