Configuring Spring Boot Interceptors: URL‑Based and Annotation‑Based Approaches
This article explains how to configure Spring Boot interceptors using both URL‑pattern matching and custom annotations, provides the necessary Java code for the interceptors and constant definitions, and shows how to register them in a @Configuration class for comprehensive request handling.
Spring Boot interceptor configuration is similar to Spring MVC with a few adjustments; the article introduces two common interceptor types: one based on URL patterns and another based on custom annotations.
1. URL‑based interceptor
public class LoginInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String path = request.getServletPath();
if (path.matches(Const.NO_INTERCEPTOR_PATH)) {
// skip interception for excluded paths
return true;
} else {
// place your interception logic here (e.g., cache, session, permission checks)
System.out.println("====================================");
return true;
}
}
}The key line path.matches(Const.NO_INTERCEPTOR_PATH) uses a regular‑expression to match URLs.
public class Const {
public static final String SUCCESS = "SUCCESS";
public static final String ERROR = "ERROR";
public static final String FIALL = "FIALL";
public static final String SESSION_USER = "loginedAgent"; // user object
public static final String SESSION_LOGINID = "sessionLoginID"; // login ID
public static final String SESSION_USERID = "sessionUserID"; // user ID
public static final String SESSION_USERNAME = "sessionUserName";
public static final Integer PAGE = 10; // default page size
public static final String SESSION_URL = "sessionUrl"; // recorded URL
public static final String SESSION_SECURITY_CODE = "sessionVerifyCode"; // captcha
public static final int TIMEOUT = 1800; // seconds
public static final String ON_LOGIN = "/logout.htm";
public static final String LOGIN_OUT = "/toLogout";
// URLs that do not require interception
public static final String NO_INTERCEPTOR_PATH = ".*/((.css)|(.js)|(images)|(login)|(anon)).*";
}2. Annotation‑based interceptor
/**
* Apply this annotation on controller methods that require login verification
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired { } public class AuthorityInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!(handler instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
if (methodAnnotation != null) {
// place your interception logic here (e.g., cache, session, permission checks)
System.out.println("====================================");
return true;
}
return true;
}
}3. Registering the interceptors
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// Intercept all requests; actual login requirement is decided by @LoginRequired
registry.addInterceptor(LoginInterceptor()).addPathPatterns("/**");
registry.addInterceptor(AuthorityInterceptor()).addPathPatterns("/**");
}
@Bean
public LoginInterceptor LoginInterceptor() {
return new LoginInterceptor();
}
@Bean
public AuthorityInterceptor AuthorityInterceptor() {
return new AuthorityInterceptor();
}
}Key points: the class must be annotated with @Configuration so that Spring loads it at startup; avoid using the deprecated WebMvcConfigurerAdapter (use WebMvcConfigurer instead); and be aware that extending WebMvcConfigurationSupport may disable default static resource handling due to the @ConditionalOnMissingBean(WebMvcConfigurationSupport.class) condition.
Overall, by moving the interceptor definitions and registration into a Spring Boot configuration class, developers can leverage the same request‑handling capabilities of Spring MVC within a Spring Boot application.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
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.