Elegant configuration of interceptors in Spring Boot

In fact, the configuration mode of spring boot interceptor is similar to that of spring MVC. Only a few small changes need to be noticed. Here are two kinds of commonly used interceptors:

I. Interceptor Based on URL:

public class LoginInterceptor extends HandlerInterceptorAdapter{
	/**
     * Call before request processing (before Controller method call)
     * Interceptor Based on URL
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getServletPath();
        if (path.matches(Const.NO_INTERCEPTOR_PATH)) {
        	//No need to intercept directly
            return true;
        } else {
        	// This describes the things you need to do to intercept, such as fetching cache, SESSION, permission judgment, etc
            System.out.println("====================================");
            return true;
        }
    }
}

Key code: path.matches (const.no'intersector'path is the url based on regular matching.

/**
 * @author 	BianP
 * @explain Constant class
 */
public class Const {

    public static final String SUCCESS = "SUCCESS";
    public static final String ERROR = "ERROR";
    public static final String FIALL = "FIALL";
    /**********************Objects and individuals****************************/
    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"; // Current user object ID number

    public static final String SESSION_USERNAME = "sessionUserName"; // Current user object ID number
    public static final Integer PAGE = 10; // Default page number
    public static final String SESSION_URL = "sessionUrl"; // Recorded url
    public static final String SESSION_SECURITY_CODE = "sessionVerifyCode"; // Login page verification code
    // Time cache time
    public static final int TIMEOUT = 1800;// second
	public static final String ON_LOGIN = "/logout.htm";
	public static final String LOGIN_OUT = "/toLogout";
    // Do not validate URL anon: do not validate / authc: controlled
    public static final String NO_INTERCEPTOR_PATH =".*/((.css)|(.js)|(images)|(login)|(anon)).*";
}

2. Annotation based interceptor

① create annotation:

/**
 * Use this annotation on the method of the Controller that requires login authentication
 */
@Target({ElementType.METHOD})// Available on method name
@Retention(RetentionPolicy.RUNTIME)// Valid at run time
public @interface LoginRequired {
	
}

② create Interceptor:

public class AuthorityInterceptor extends HandlerInterceptorAdapter{
	
	 @Override
	 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
	 	// If it is not mapped to a method directly through
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // ①: START method annotation level interceptor
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // Determine whether the interface needs to be logged in
        LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
        // With @ LoginRequired annotation, authentication is required
        if (methodAnnotation != null) {
            // This describes the things you need to do to intercept, such as fetching cache, SESSION, permission judgment, etc
            System.out.println("====================================");
            return true;
        }
        return true;
	}
}

3. Add the interceptor to the configuration, which is equivalent to what the configuration file does in spring MVC:

/**
 * The same webmvc interception configuration as spring MVC
 * @author BIANP
 */
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurationSupport {
	 @Override
	 public void addInterceptors(InterceptorRegistry registry) {
        // Block all requests, and determine whether login is required by judging whether there is @ LoginRequired annotation
        registry.addInterceptor(LoginInterceptor()).addPathPatterns("/**");
        registry.addInterceptor(AuthorityInterceptor()).addPathPatterns("/**");
        super.addInterceptors(registry);
	 }
	 
	 @Bean
	 public LoginInterceptor LoginInterceptor() {
		 return new LoginInterceptor();
	 }
	 
	 @Bean
	 public AuthorityInterceptor AuthorityInterceptor() {
		 return new AuthorityInterceptor();
	 }
}

Be sure to add the @ Configuration annotation, which will be loaded at startup. There are also some tutorials using "WebMvcConfigurerAdapter", which is the same, but it will prompt that this method is out of date.

In fact, many things of spring MVC can be used in spring boot. Just change the mode of Configuration file to the corresponding @ Configuration class.

Keywords: Programming Spring Session

Added by garry on Mon, 09 Dec 2019 01:59:42 +0200