Configuring SpringBoot Interceptors: URL‑Based and Annotation‑Based Approaches

This article explains how to configure SpringBoot interceptors, covering both URL‑based and annotation‑based implementations, provides full Java code examples, and shows how to register them in a WebMvcConfigurer while noting recent Spring framework changes.

Architect's Tech Stack
Architect's Tech Stack
Architect's Tech Stack
Configuring SpringBoot Interceptors: URL‑Based and Annotation‑Based Approaches

SpringBoot interceptor configuration is similar to Spring MVC with a few minor differences that need attention.

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 matched paths
            return true;
        } else {
            // Place custom 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 decide whether the request should be intercepted.

2. Constant Class Used by the Interceptor

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";
    // No‑intercept path pattern (static resources, login, anon, etc.)
    public static final String NO_INTERCEPTOR_PATH = ".*/((.css)|(.js)|(images)|(login)|(anon)).*";
}

3. Annotation‑Based Interceptor

First, define a custom annotation that marks controller methods requiring login:

/**
 * Apply this annotation to controller methods that need login verification.
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {}

Then implement an interceptor that checks for the annotation at runtime:

public class AuthorityInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true; // Not a method mapping, allow
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
        if (methodAnnotation != null) {
            // Custom logic for authenticated requests (e.g., session, permission checks)
            System.out.println("====================================");
            return true;
        }
        return true;
    }
}

4. Registering Interceptors in SpringBoot

@Configuration
public class WebConfigurer implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // Intercept all requests; actual login check 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();
    }
}

Important notes:

The class must be annotated with @Configuration so that Spring loads it at startup.

Older tutorials may use WebMvcConfigurerAdapter, which was deprecated after Spring 5.0; prefer implementing WebMvcConfigurer directly.

Using WebMvcConfigurationSupport can disable the default static‑resource locations ( classpath:/META‑resources/, classpath:/resources/, etc.) because @ConditionalOnMissingBean(WebMvcConfigurationSupport.class) prevents auto‑configuration.

5. Promotional Section (Non‑Technical)

The author also advertises a compiled collection of interview questions titled “第2版:互联网大厂面试题”, containing 96 files, 3,265 pages, and 3,625 PDF pages, with a QR code for download. This part is promotional and not related to the technical tutorial.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

InterceptorSpringBoot
Architect's Tech Stack
Written by

Architect's Tech Stack

Java backend, microservices, distributed systems, containerized programming, and more.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.