Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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:

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 response, Object handler) throws Exception {
        …
      return true;
    }
    
    @Override
    public void postHandle(HttpServletRequest request,
        HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
      ...
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request,
        HttpServletResponse response...