Spring MVC HandlerInterceptor: Request Lifecycle Control

Spring MVC’s HandlerInterceptor interface provides a mechanism to intercept HTTP requests at key points in request-processing pipeline, enabling cross-cutting concerns like authentication, logging, or performence monitoring without modifying individual controller logic.

Interface Contract

The HandlerInterceptor interface defines three methods that are invoked at specific stages of request handling: - preHandle: Executed before the controller method is invoked. Returns a boolean indicating whether the request should proceed. Returning false halts execution and prevents the controller from being called.

  • postHandle: Invoked after the controller method completes but before the view is rendered. Allows modification of the model or view attributes.
  • afterCompletion: Called after the full request cycle completes, including view rendering. Ideal for cleanup operations such as closing resources or logging response times.

These methods are invoked in sequence for each registered interceptor, with postHandle and afterCompletion executing in reverse order to ensure proper resource menagement.

Custom Interceptor Implementation

Rather than implementing the full interface, extend HandlerInterceptorAdapter to override only the methods of interest: ``` import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

public class SessionValidationInterceptor extends HandlerInterceptorAdapter {

@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
    String sessionId = req.getSession().getId();
    if (sessionId == null || req.getSession().getAttribute("user") == null) {
        res.sendRedirect("/login");
        return false;
    }
    System.out.println("✅ Session validated for ID: " + sessionId);
    return true;
}

@Override
public void postHandle(HttpServletRequest req, HttpServletResponse res, Object handler, ModelAndView mv) throws Exception {
    System.out.println("🔧 Post-processing: Model size = " + (mv != null ? mv.getModel().size() : 0));
}

@Override
public void afterCompletion(HttpServletRequest req, HttpServletResponse res, Object handler, Exception ex) throws Exception {
    System.out.println("🧹 Request completed. Exception: " + (ex != null ? ex.getClass().getSimpleName() : "None"));
}

}


</div>### Configuration via Java Config

Register interceptors using `WebMvcConfigurer` (deprecated in Spring Boot 2.7+, replaced by `WebMvcConfigurer` in newer versions): <div class="code-block">```
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public SessionValidationInterceptor sessionInterceptor() {
        return new SessionValidationInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(sessionInterceptor())
                .addPathPatterns("/api/**", "/dashboard/**")
                .excludePathPatterns("/login", "/register", "/assets/**");
    }
}

XML-Based Configuration

For legacy applications using XML configuration, interceptors are declared within the <mvc:interceptors> element: ``` mvc:interceptors mvc:interceptor <mvc:mapping path="/api/"/> <mvc:mapping path="/dashboard/"/> <mvc:exclude-mapping path="/login"/> <mvc:exclude-mapping path="/register"/> </mvc:interceptor> </mvc:interceptors>


</div>Use `<mvc:exclude-mapping>` to bypass interception for specific paths, ensuring public endpoints remain accessible without session validation.

Interceptors are particularly effective for stateful operations tied to HTTP sessions, request headers, or request context that must be validated or enriched before reaching business logic.

Tags: SpringMVC HandlerInterceptor WebMvcConfigurer JavaWeb HTTPInterceptor

Posted on Tue, 18 Aug 2026 16:18:22 +0000 by Bmen