WebMvcConfigurationSupport 静态资源失效问题

在使用SpringBoot做项目时,需要使用拦截器判断用户是否登陆,来决定用户是否能访问某些页面。
起初,通过继承来WebMvcConfigurerAdapter

package com.donglei.myblog.interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.*;
@SpringBootConfiguration
public class AdminLoginAdapter extends WebMvcConfigurerAdapter {
    @Autowired
    AdminLoginInterceptor adminLoginInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(adminLoginInterceptor).addPathPatterns("/admin").excludePathPatterns("/login/**");
        registry.addInterceptor(adminLoginInterceptor).addPathPatterns("/index");
        super.addInterceptors(registry);
    }

但是由于SpringBoot 2.0之后,就将WebMvcConfigurerAdapter废弃使用了,推荐使用WebMvcConfigurationSupport,但是使用WebMvcConfigurationSupport后发现网页不能获取到静态资源。这里提供两种解决方法:

一、重写 addResourceHandlers()方法,加入静态文件路径

package com.donglei.myblog.interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.*;

@SpringBootConfiguration
public class AdminLoginAdapter extends WebMvcConfigurationSupport {
    @Autowired
    AdminLoginInterceptor adminLoginInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(adminLoginInterceptor).addPathPatterns("/admin").excludePathPatterns("/login/**");
        registry.addInterceptor(adminLoginInterceptor).addPathPatterns("/index");
        super.addInterceptors(registry);
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    //重写这个方法,映射静态资源文件
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/resources/")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/public/");
        super.addResourceHandlers(registry);
    }
}

实践证明,这种方法行之有效,但是有的朋友可能表示,这种方法还是有问题,那就第二种方法,实现WebMvcConfigurer接口

二、实现WebMvcConfigurer接口


package com.donglei.myblog.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.*;
@SpringBootConfiguration
public class AdminLoginAdapter implements WebMvcConfigurer {

    @Autowired
    AdminLoginInterceptor adminLoginInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(adminLoginInterceptor).addPathPatterns("/admin").excludePathPatterns("/login/**");
        registry.addInterceptor(adminLoginInterceptor).addPathPatterns("/index");
        //super.addInterceptors(registry);
    }
}

这样,就解决了WebMvcConfigurationSupport 静态资源失效问题

你可能感兴趣的:(各种错误异常,Java)