Springboot learning (1) Interceptor

  1. The WebMvcConfigurerAdapter interceptor was abolished after springboot2.1. When customizing the interceptor, you need to inherit the WebMvcConfigurationSupport class to override the addInterceptors () method to add our custom interceptor.
  2. About the problem that static resources cannot be accessed after configuring a custom connector

The addResourceHandlers () method needs to be rewritten in the inherited WebMvcConfigurationSupport class as follows:

package com.lhb.blog.interceptor;

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.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class LoginConfig extends WebMvcConfigurationSupport {

    @Autowired
    private LoginInterceptor interceptor;

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(interceptor).addPathPatterns("/admin/**")
                .excludePathPatterns("/admin/")
                .excludePathPatterns("/admin/login");
    }

    /**
     * Configure static resource access
     * @param registry
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        if(!registry.hasMappingForPattern("/webjars/**")){
            registry.addResourceHandler("/webjars/**")
                    .addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
        if (!registry.hasMappingForPattern("/**")){
            registry.addResourceHandler("/**")
                    .addResourceLocations("classpath:/META-INF/resources/")
                    .addResourceLocations("classpath:/resources/")
                    .addResourceLocations("classpath:/static/")
                    .addResourceLocations("classpath:/public/");
        }
    }
}

  





Guess you like

Origin www.cnblogs.com/lihuibin/p/12677871.html
Recommended