springboot2.0以上,静态资源无法访问,及设置拦截器后,login登录页面设置不拦截,还是被拦截到的问题_声明了还是会被拦截器拦截-程序员宅基地

技术标签: java  SpringBoot  

在springboot 2.0以上,在配置文件application.yml中设置静态资源,依然无法访问,如下图在这里插入图片描述

在这里插入图片描述

先讲解决方法:

新建一个WebMvcConfig.java文件,继承WebMvcConfigurationSupport来设置静态资源路径

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    
        super.addResourceHandlers(registry);
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
}

这样就可以访问静态资源文件了,至于application.yml已经不需要写了,原因可能是@Ordered加载顺序的问题,这个希望有大佬指教一下

那问题就来了,这样子是可以访问静态资源文件的,但是如果在WebMvcConfig加一个拦截器,如下:
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    

    @Autowired
    private UserInterceptor userInterceptor;

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
    
        registry.addInterceptor(userInterceptor).addPathPatterns("/**");
    }

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

}
就又无法访问了,原因是springboot 2.0继承了spring5,而springboot 1.5x的是继承spring4.3,spring4.3源码如下:
/**
 * Return a handler mapping ordered at Integer.MAX_VALUE-1 with mapped
 * resource handlers. To configure resource handling, override
 * {@link #addResourceHandlers}.
 */
@Bean
public HandlerMapping resourceHandlerMapping() {
    
    ResourceHandlerRegistry registry = new ResourceHandlerRegistry(this.applicationContext,
				this.servletContext, mvcContentNegotiationManager());
    addResourceHandlers(registry);
 
    AbstractHandlerMapping handlerMapping = registry.getHandlerMapping();
    if (handlerMapping != null) {
    
        handlerMapping.setPathMatcher(mvcPathMatcher());
        handlerMapping.setUrlPathHelper(mvcUrlPathHelper());
        // 此处固定添加了一个Interceptor
        handlerMapping.setInterceptors(new ResourceUrlProviderExposingInterceptor(mvcResourceUrlProvider()));
        handlerMapping.setCorsConfigurations(getCorsConfigurations());
		}
    else {
    
        handlerMapping = new EmptyHandlerMapping();
    }
    return handlerMapping;
}

而spring5.x的源码如下:

	/**
	 * Return a handler mapping ordered at Integer.MAX_VALUE-1 with mapped
	 * resource handlers. To configure resource handling, override
	 * {@link #addResourceHandlers}.
	 */
	@Bean
	@Nullable
	public HandlerMapping resourceHandlerMapping(
			@Qualifier("mvcUrlPathHelper") UrlPathHelper urlPathHelper,
			@Qualifier("mvcPathMatcher") PathMatcher pathMatcher,
			@Qualifier("mvcContentNegotiationManager") ContentNegotiationManager contentNegotiationManager,
			@Qualifier("mvcConversionService") FormattingConversionService conversionService,
			@Qualifier("mvcResourceUrlProvider") ResourceUrlProvider resourceUrlProvider) {
    

		Assert.state(this.applicationContext != null, "No ApplicationContext set");
		Assert.state(this.servletContext != null, "No ServletContext set");

		ResourceHandlerRegistry registry = new ResourceHandlerRegistry(this.applicationContext,
				this.servletContext, contentNegotiationManager, urlPathHelper);
		addResourceHandlers(registry);

		AbstractHandlerMapping handlerMapping = registry.getHandlerMapping();
		if (handlerMapping == null) {
    
			return null;
		}
		handlerMapping.setPathMatcher(pathMatcher);
		handlerMapping.setUrlPathHelper(urlPathHelper);
		// 此处是将所有的HandlerInterceptor都添加了(包含自定义的HandlerInterceptor)
		handlerMapping.setInterceptors(getInterceptors(conversionService, resourceUrlProvider));
		handlerMapping.setCorsConfigurations(getCorsConfigurations());
		return handlerMapping;
	}
	
	/**
	 * Provide access to the shared handler interceptors used to configure
	 * {@link HandlerMapping} instances with.
	 * <p>This method cannot be overridden; use {@link #addInterceptors} instead.
	 */
	protected final Object[] getInterceptors(
			FormattingConversionService mvcConversionService,
			ResourceUrlProvider mvcResourceUrlProvider) {
    
		if (this.interceptors == null) {
    
			InterceptorRegistry registry = new InterceptorRegistry();
			// 此处传入新new的registry对象,在配置类当中设置自定义的HandlerInterceptor后即可获取到
			addInterceptors(registry);
			registry.addInterceptor(new ConversionServiceExposingInterceptor(mvcConversionService));
			registry.addInterceptor(new ResourceUrlProviderExposingInterceptor(mvcResourceUrlProvider));
			this.interceptors = registry.getInterceptors();
		}
		return this.interceptors.toArray();
	}

从源码当中可以看出,使用spring 5.x时,静态资源也会执行自定义的拦截器,因此在配置拦截器的时候需要指定排除静态资源的访问路径,即配置改为如下即可:

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    

    @Autowired
    private UserInterceptor userInterceptor;

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
    
        registry.addInterceptor(userInterceptor).addPathPatterns("/**")
                .excludePathPatterns("/auth/login")
                .excludePathPatterns("/error")
                .excludePathPatterns("/static/**");
    }

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

}

到这里,如果不添加/error,有时候在进入登录页面的时候,会被拦截器HandlerInterceptor拦截,原因是/error是默认错误跳转页面,也被默认拦截了,如果不exclude,在登陆时候就会被拦截

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_39236419/article/details/106855377

智能推荐

CPU如何跑分_cpu跑分教程-程序员宅基地

文章浏览阅读1k次。烤CPU的时候,占用率满了,CPU频率的槽有一些还是空的…… 有没有能跑分的软件?好像有的【聊电Jing】你的CPU性能如何? 来跑个分测试看看吧! | Cinebench R15 & R20 使用教学_哔哩哔哩_bilibili 好像还是免费的Cinebench - Maxon Cinebench - Microsoft Store Apps 频率为什么就是超不过3Ghz? 多核,100度了? 可能频率最高只能这么高,再高可能就烧掉了…… 多核结果.................._cpu跑分教程

最大流问题的Ford-Fulkerson解法_ford capacity 详解-程序员宅基地

文章浏览阅读498次。这是一种方法,而不是算法,因为它包含具有不同运行时间的几种实现。该方法依赖于三种重要思想:残留网络,增广路径和割我们先简单介绍下Ford-Fulkerson方法的基本思想。首先需要了解的是Ford-Fulkerson是一种迭代的方法。开始时,对所有的u,v属于V,f(u,v)=0(这里f(u,v)代表u到v的边当前流量),即初始状态时流的值为0。在每次迭代中,可以通过寻找一个“增广路径”来增加_ford capacity 详解

Windows10下多版本CUDA的安装与切换 超详细教程_cuda版本-程序员宅基地

文章浏览阅读1.9w次,点赞69次,收藏379次。当我们跑深度学习的代码时,有时会遇到上古的代码,环境比较老,是低版本的 CUDA,此时我们就需要多个 CUDA 版本,并能灵活切换。本文是在已有CUDA11.2的环境下安装CUDA9.2。Windows10下多版本CUDA的安装与切换保姆级教学。_cuda版本

C语言——数组逆置(内含递归实现)-程序员宅基地

文章浏览阅读5k次,点赞5次,收藏25次。一.什么是数组的逆置呢?int a[10]={1,2,3,4,5,6,7,8,9,10};将数组变为 a[10]={10,9,8,7,6,5,4,3,2,1};这就叫做数组的逆置。二.1.循环实现数组的逆置这个是我们在初学C语言时最容易的实现方法!a.通过for循环实现//通过循环完成对数组的逆置#include<stdio.h>#define size 10void Inversion(int[], int);int main(void){ i_数组逆置

esp32-cam Thonny 烧录以及通信-程序员宅基地

文章浏览阅读229次,点赞4次,收藏3次。链接:https://pan.baidu.com/s/1cBsrCJ_TATFsuVhVdr0VmA?IO1和GND不再短接。重新插拔一下,就可以了。

字符,字节和编码-程序员宅基地

文章浏览阅读39次。级别:中级摘要:本文介绍了字符与编码的发展过程,相关概念的正确理解。举例说明了一些实际应用中,编码的实现方法。然后,本文讲述了通常对字符与编码的几种误解,由于这些误解而导致乱码产生的原因,以及消除乱码的办法。本文的内容涵盖了“中文问题”,“乱码问题”。掌握编码问题的关键是正确地理解相关概念,编码所涉及的技术其实是很简单的。因此,阅读本文时需要慢读多想,多思考。引言“字符与编码”...

随便推点

话题的发布与订阅_话题订阅频率和发布频率一样-程序员宅基地

文章浏览阅读2.6k次,点赞3次,收藏11次。Ros话题发布与订阅节点的编写(C++)_话题订阅频率和发布频率一样

Qt Creator 安装 VLD_qtcreater vld-程序员宅基地

文章浏览阅读509次。Qt Creator 安装 VLD2015-04-14 16:52:55你好L阅读数 2325更多分类专栏:qt版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。本文链接:https://blog.csdn.net/lin_jianbin/article/details/45044459一、环境说明1、VLD内存..._qtcreater vld

Linux 开发环境工具[zt]-程序员宅基地

文章浏览阅读120次。软件集成开发环境(代码编辑、浏览、编译、调试)Emacs http://www.gnu.org/software/emacs/Source-Navigator 5.2b2 http://sourceforge.net/projects/sourcenavAnjuta http://anjuta.sourceforge...._linux上安装flawfinder

java小易——Spring_spring的beanfactory是hashmap吗-程序员宅基地

文章浏览阅读109次。SpringIoC DI AOPspring底层用的是ConcurrentHashMap解耦合:工厂模式:需要一个模板控制反转 IoC将原来有动作发起者(Main)控制创建对象的行为改成由中间的工厂来创建对象的行为的过程叫做IoC一个类与工厂之间如果Ioc以后,这个时候,动作发起者(Main)已经不能明确的知道自己获得到的对象,是不是自己想要的对象了,因为这个对象的创建的权利与交给我这个对象的权利全部转移到了工厂上了所用包:DOM4j解析XML文件lazy-init = _spring的beanfactory是hashmap吗

温故而知新:部分常见的图像数学运算处理算法的用途_图像处理算啊-程序员宅基地

文章浏览阅读1.3k次,点赞29次,收藏24次。本文将图像处理中常用的数学运算算法及其对图像的作用做了个汇总介绍,有助于图像处理时针对对应场景快速选择合适的数学算法。_图像处理算啊

EM Agent Fatal agent error: State Manager failed at Startup_check agent status retcode=1-程序员宅基地

文章浏览阅读1.1k次。EM 不定期异常宕机,问题重复出现,之前几次因为忙于其它事,无力兼顾,等回头处理时,发现EM已恢复正常。这次问题又重现,准备彻底解决,过程如下:1. 重新启动EM失败,报错:/u01/oracle/agent/core/12.1.0.5.0/bin/emctl status agentOracle Enterprise Manager Cloud Control 12c Relea_check agent status retcode=1