How do Spring Boot 2.X add interceptors?

Keywords: Java Spring Fragment Session

Recently, a project has been built using SpringBoot 2.X. Most of the interfaces need login checking, so we intend to use annotation + interceptor to implement it, and record the implementation process here.


First, the principle of implementation

1. Customize a comment @NeedLogin and add it to the interface method or class method if the interface needs login checking.
2. Logon interceptor LoginInterceptor checks whether there are @NeedLogin annotations in the method or class of the interface, and logon checks if there are annotations.

II. Major Codes

1. NeedLogin annotation code

package com.example.helloSpringBoot.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

 * Login annotation
 * @Author: Java Fragment
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface NeedLogin {

2. Login Interceptor

package com.example.helloSpringBoot.config;

import com.example.helloSpringBoot.annotation.NeedLogin;
import com.example.helloSpringBoot.util.WxUserInfoContext;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

 * Logon interceptor
 * @Author: Java Fragment
public class LoginInterceptor implements HandlerInterceptor {

    //This method is executed before accessing the interface. We only need to write the business logic to verify the login status here to verify the login status before the user calls the specified interface.
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            NeedLogin needLogin = ((HandlerMethod) handler).getMethodAnnotation(NeedLogin.class);
            if (null == needLogin) {
                needLogin = ((HandlerMethod) handler).getMethod().getDeclaringClass()
            // Check login if you have login validation annotations
            if (null != needLogin) {
                WxUserInfoContext curUserContext = (WxUserInfoContext) request.getSession()
                //If session No, not logged in.
                if (null == curUserContext) {
                    response.getWriter().write("Not logged in!");
                    return false;

        return true;

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

3. Configuration of interceptors

package com.example.helloSpringBoot.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

 * WebConfig
 * @Author: Java Fragment
public class WebConfig implements WebMvcConfigurer {
    private LoginInterceptor loginInterceptor;

    public void addInterceptors(InterceptorRegistry registry) {
        // Custom interceptor, add intercept path and exclude intercept path

3. Verification Code

HelloController adds two methods, testNeedLogin() adds login interception, and testNoLogin() does not require login interception.

package com.example.helloSpringBoot.controller;

import com.example.helloSpringBoot.annotation.NeedLogin;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

public class HelloController {

     * Testing does not require login
    public String testNoLogin (){
        return "The call is successful, this interface does not need login validation!-Java Broken read!";

     * Testing requires login
    public String testNeedLogin (){
        return "testNeedLogin!";

TesNeedLogin runs as follows:

TesNoLogin runs as follows:


The login interception can be achieved after the above three steps are completed. If you have any questions, please leave a message to communicate.

Full source address:


Recommended reading

1. How does Spring Boot 2.X gracefully solve cross-domain problems?
2.Redis Cluster Builds High Availability Redis Server Cluster
3. Why is single-threaded EDIS so fast?
4.Spring Boot integrates spring session to realize session sharing
5.Spring Boot Introduction - Quick Building web Projects
6. Spring Boot 2.0 Integrates Redis
7. An article on Spring MVC parameter binding
8. How can Spring MVC + Mybatis configure multiple data sources and switch?


Time-limited access to free Java-related information, covering Java, Redis, MongoDB, MySQL, Zookeeper, Spring Cloud, Dubbo/Kafka, Hadoop, Hbase, Flink and other high-concurrent distributed, large data, machine learning technology.

Data portal:

Pay attention to the following public numbers for free:


Posted by 0p3n_p0rT on Thu, 16 May 2019 19:12:35 -0700