How do spring boot add interceptors

  • 2020-06-19 10:26:04
  • OfStack

Build 1 spring boot project.

Adding interceptors requires adding an configuration


@Configuration
@ComponentScan(basePackageClasses = Application.class, useDefaultFilters = true)
public class ServletContextConfig extends WebMvcConfigurationSupport {

To facilitate the scan location, we can write an interface or entry class Application to be placed in the outermost layer of the package, so that the class and its subpackage classes are scanned.

1 resources configuration

When this class is not configured, we can modify the static file location and matching mode in application.ym:


# Specify the environment configuration file 
spring:
 profiles:
  active: dev
 #  Modify the default static path, which defaults to /** When the configuration hello.config.ServletContextConfig After this configuration fails 
 mvc:
  static-path-pattern: /static/**

However, when we inherited WebMvcConfigurationSupport and configured the scan, the above resources configuration failed and the default configuration was restored. Then we need to specify the static resource location again in this class:


@Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/").addResourceLocations("/**");
    registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
  }

The url that accesses the static resource under the static package under classpath thus matches /static/ xxx.js. By default, url matches the static file under static as/xxx.js. Although it is clean, I feel that idea will not recognize this path, so it is better to change it to a full path.

2. Interceptor configuration

Configure login interception or something else. You need to create an interceptor class to inherit from HandlerInterceptorAdapter, and then just override where you want to intercept. For example, I just intercept access methods before:


package hello.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

/**
 * Created by miaorf on 2016/8/3.
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
  private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    String authorization = request.getHeader("Authorization");
    logger.info("The authorization is: {}",authorization);
    return super.preHandle(request, response, handler);
  }
}

After writing interceptor, you need to add this interceptor to the ServletContextConfig you started creating:


@Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new LoginInterceptor())
        .addPathPatterns("/**")
        .excludePathPatterns(FAVICON_URL)
    ;
  }

The complete ServletContextConfig is:


package hello.config;

import hello.Application;
import hello.interceptor.LoginInterceptor;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 *
 */
@Configuration
@ComponentScan(basePackageClasses = Application.class, useDefaultFilters = true)
public class ServletContextConfig extends WebMvcConfigurationSupport {

  static final private String FAVICON_URL = "/favicon.ico";
  static final private String PROPERTY_APP_ENV = "application.environment";
  static final private String PROPERTY_DEFAULT_ENV = "dev";



  /**
   *  Discover if you inherit WebMvcConfigurationSupport While the, yml The relevant content of the configuration in. 
   * @param registry
   */
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/").addResourceLocations("/**");
    registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
  }


  /**
   *  configuration servlet To deal with 
   */
  @Override
  public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
  }

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new LoginInterceptor())
        .addPathPatterns("/**")
        .excludePathPatterns(FAVICON_URL)
    ;
  }

}

github address: https: / / github com chenxing12 / spring boot -- demo

demo source code: ES66en-ES67en-demo_jb51.ES70en


Related articles: