Executing some code before and after controllers using interceptors

In this recipe, you'll learn how, with interceptors, we can execute some code across all controllers at different moments of a request workflow with the preHandle(), postHandle(), and afterCompletion() hooks:

Executing some code before and after controllers using interceptors

Interceptors are used for authentication, logging, and profiling (among others).

How to do it…

Here are the steps to create and register an interceptor:

  1. Create a class extending HandlerInterceptorAdapter:
    public class PerformanceInterceptor extends HandlerInterceptorAdapter {
  2. Override the methods you want to use:
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse ...

Get Spring Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.