Mastering Spring Interceptors: Control Requests, Logging, and Security
This article explains Spring Interceptors, their relationship with WebApplicationContext, various types, configuration methods, execution flow, advanced features, differences from filters, and provides practical logging and authentication examples with code snippets.
Interceptor Overview
In the Spring framework, an Interceptor is a powerful mechanism that allows developers to insert custom logic at various stages of request processing. WebApplicationContext provides the underlying support for registering and managing interceptors.
Typical use cases include permission validation, logging, performance monitoring, transaction management, and generic behavior injection.
Relationship between Interceptor and WebApplicationContext
WebApplicationContext is the Spring Web IoC container extension that inherits from ApplicationContext and adds web‑specific features. Interceptors are registered and managed through this context, becoming part of the request handling pipeline.
public interface WebApplicationContext extends ApplicationContext {
String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT";
ServletContext getServletContext();
}Interceptor Types
HandlerInterceptor
The most common interceptor interface, defining three key methods:
public interface HandlerInterceptor {
default boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
return true;
}
default void postHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView) throws Exception { }
default void afterCompletion(HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex) throws Exception { }
}AsyncHandlerInterceptor
Extension of HandlerInterceptor that adds support for asynchronous processing.
WebRequestInterceptor
Similar to HandlerInterceptor but works with the more generic WebRequest abstraction and does not depend on the Servlet API.
Interceptor Configuration
Java‑based configuration:
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoggingInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/static/**");
registry.addInterceptor(new AuthInterceptor())
.addPathPatterns("/admin/**");
}
}Annotation‑based configuration:
@Component
public class MyInterceptor implements HandlerInterceptor {
// implement methods
}
@Configuration
public class InterceptorConfig {
@Autowired
private MyInterceptor myInterceptor;
@Bean
public WebMvcConfigurer adapter() {
return new WebMvcConfigurer() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor);
}
};
}
}Interceptor Execution Flow
preHandle : called before the handler; returning true continues processing, false aborts.
postHandle : called after the handler but before view rendering; can modify ModelAndView.
afterCompletion : called after the complete request has finished; suitable for resource cleanup.
Advanced Features
Interceptor Order Control
Order can be set to control the sequence of multiple interceptors:
registry.addInterceptor(new InterceptorA()).order(1);
registry.addInterceptor(new InterceptorB()).order(2);Path Matching Patterns
Supports Ant‑style patterns, e.g., ? matches one character, * matches zero or more characters, ** matches zero or more directories.
Asynchronous Request Handling
For async requests, afterConcurrentHandlingStarted is invoked instead of postHandle and afterCompletion.
Interceptor vs. Filter
Feature
Interceptor
Filter
Container Dependency
Spring container
Servlet container
Scope
Spring MVC requests
All requests entering the container
Access Object
Can access Handler and method info
Only ServletRequest/Response
Execution Timing
Inside DispatcherServlet
Outside DispatcherServlet
Dependency Injection
Supported
Not supported
Practical Examples
Logging Interceptor
public class LoggingInterceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
long startTime = System.currentTimeMillis();
request.setAttribute("startTime", startTime);
logger.info("Request URL: {} : Start Time={}", request.getRequestURL(), startTime);
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) {
long startTime = (Long) request.getAttribute("startTime");
long endTime = System.currentTimeMillis();
logger.info("Request URL: {} : End Time={} : Time Taken={}ms",
request.getRequestURL(), endTime, (endTime - startTime));
}
}Authentication Interceptor
public class AuthInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
HttpSession session = request.getSession();
if (session.getAttribute("user") == null) {
response.sendRedirect("/login");
return false;
}
return true;
}
}Demo Results
Intercepted request:
Non‑intercepted request:
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JD Cloud Developers
JD Cloud Developers (Developer of JD Technology) is a JD Technology Group platform offering technical sharing and communication for AI, cloud computing, IoT and related developers. It publishes JD product technical information, industry content, and tech event news. Embrace technology and partner with developers to envision the future.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
