栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springBoot静态资源路径映射配置不生效,浏览器访问为404(addResourceHandler,addResourceLocations springboot-2.6.x不生效)的可能原因

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springBoot静态资源路径映射配置不生效,浏览器访问为404(addResourceHandler,addResourceLocations springboot-2.6.x不生效)的可能原因

springBoot静态资源路径映射配置不生效(addResourceHandler,addResourceLocations springboot-2.6.x不生效)的可能原因

静态资源路径映射配置的大致代码如下:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer _{
_private static String localhostPath = “D:学习资料学习笔记springboot+vue+elementUI-个人博客images”;

@Override
public void addResourceHandlers_(ResourceHandlerRegistry registry) {_
// registry.addResourceHandler(“虚拟路径”).addResourceLocations(“file:本地资源路径”);
registry.addResourceHandler_(“/image/**”).addResourceLocations(_“file:” + localhostPath);

}
}

随后发现配置不生效,使用浏览器打开都是404,已确认addResourceHandler和addResourceLocations所填的值均是正确的

当前使用的springboot版本是2.6.7版本

随后将springboot依赖修改成2.5.8版本后,静态资源映射就生效了

Springboot-2.6.7版本无效,springboot- 2.5.8版本有效

因此可能是相关的spring的源代码修改了

后咨询前辈@码农小胖哥

码农小胖哥的博客_CSDN博客-Spring Security与OAuth2,java,spring security领域博主

知道是Springboot-2.6.x所使用到的spring mvc-5.3.x 默认的路径匹配策略改变了:

Spring MVC 处理程序映射匹配请求路径的默认策略已从 AntPathMatcher 更改为PathPatternParser。

Actuator端点现在也使用基于 PathPattern 的 URL 匹配。需要注意的是,Actuator端点的路径匹配策略无法通过配置属性进行配置。

如果需要将默认切换回 AntPathMatcher,可以将 spring.mvc.pathmatch.matching-strategy 设置为 ant-path-matcher,比如下面这样:

spring.mvc.pathmatch.matching-strategy=ant-path-matcher

加上这一配置后,

Springboot-2.6.7的静态资源路径映射也可以正常使用了。

解决方法总结:

1.修改springboot版本为低版本,如2.5.x

2.添加配置 spring.mvc.pathmatch.matching-strategy=ant-path-matcher

3.使用低版本的spring-mvc依赖

knife4j(swagger) 在springboot- 2.6以上版本使用出现问题也可以尝试使用这些方法。

以后遇到配置不生效的时候,得注意一下是不是版本的原因。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1031317.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号