Configuring an Interceptor
Register a custom interceptor by implementing WebMvcConfigurer and overriding addInterceptors. Define URL patterns to match and exclude. A global pattern such as /** also targets static resources, so explicit exclusions are necessary.
@Configuration
public class WebInterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new SessionAuthInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/", "/auth/login", "/assets/**", "/static/**");
}
}
Building a Session Authentication Interceptor
Implement HandlerInterceptor to inspect requests before they reach a controller. The preHandle method is the appropriate hook for validating session state and redirecting unauthenticated traffic.
@Slf4j
public class SessionAuthInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
String uri = req.getRequestURI();
log.info("Intercepting request: {}", uri);
Object user = req.getSession().getAttribute("currentUser");
if (user != null) {
return true;
}
req.setAttribute("error", "Authentication required");
req.getRequestDispatcher("/auth/login").forward(req, resp);
return false;
}
@Override
public void postHandle(HttpServletRequest req, HttpServletResponse resp, Object handler, ModelAndView mv) throws Exception {
log.info("postHandle invoked for view: {}", mv);
}
@Override
public void afterCompletion(HttpServletRequest req, HttpServletResponse resp, Object handler, Exception ex) throws Exception {
if (ex != null) {
log.error("afterCompletion detected exception", ex);
}
}
}
How the Inetrceptor Chain Works
When a request arrives, Spring resolves a HandlerExecutionChain containing the destination controller and a list of applicable interceptors. The fraemwork then drives the chain through three distinct phases.
1. Pre-Handle Forward Pass
Interceptors run preHandle in registration order.
- Success (
true): The chain advances to the next interceptor. - Failure (
false): The framework halts immediately and walks backward, callingafterCompletionon every interceptor that previously returnedtrue. The controller method is bypassed.
2. Handler Execution
If every interceptor approves the request, the target controller method executes.
3. Post-Handle Reverse Pass
After the controller returns a model or view—but before rendering—postHandle executes in reverse registration order. This phase is entirely skipped if any earlier preHandle returned false.
4. Completion Reverse Pass
The afterCompletion callbacks run in reverse order during three specific scenarios:
- An expection surfaces anywhere in the pipeline.
- A downstream
preHandlereturnsfalse. - The view renders successfully and the response is ready.
Only interceptors whose preHandle returned true participate in this final cleanup stage.