Configuring and Using Custom Interceptors in Spring MVC

Creating a Custom Interceptor by Extending HandlerInterceptorAdapter

Implementing the Interceptor Class

Create a new class that extends HandlerInterceptorAdapter and annotate it with @Component:

package com.example.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class AuditInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(AuditInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("Intercepted request: {}", request.getRequestURI());

        HttpSession session = request.getSession();
        if (!StringUtils.isEmpty(session.getAttribute("userId"))) {
            return true;
        } else {
            response.sendRedirect("/logins");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // Execute after controller processing but before view rendering
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // Execute after entire request completes, useful for cleanup
    }
}

Understanding Interceptor Lifecycle

preHandle method:

  • Executes before the controller processes the request
  • Multiple interceptors form a chain and execute sequentially
  • All preHandle methods are invoked before the controller is called
  • Returning false terminates the request immediately

postHandle method:

  • Executes after the controller but before view rendering
  • Allows modification of the ModelAndView object
  • Interceptors execute in reverse order of declaration

afterCompletion method:

  • Executes after the entire request completes, including view rendering
  • Ideal for resource cleanup operations

Registering the Custom Interceptor

Creating the Interceptor Configuration Class

Extend WebMvcConfigurationSupport and override addInterceptors:

package com.example.interceptor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration registration = registry.addInterceptor(auditInterceptor());
        
        // Paths to exclude from interception
        registration.excludePathPatterns("/logins");
        registration.excludePathPatterns("/loginout");
        
        // Paths to intercept
        registration.addPathPatterns("/**");
    }

    @Bean
    public AuditInterceptor auditInterceptor() {
        return new AuditInterceptor();
    }
}

With this configuration, all endpoints except /logins and /loginout will be intercepted.

Tags: Spring MVC interceptor java Web Configuration HandlerInterceptorAdapter

Posted on Thu, 13 Aug 2026 16:26:13 +0000 by dubrubru