SpringBoot无法访问静态资源:无GET请求映射告警,配置文件设置无效求助
SpringBoot静态资源无法访问的解决方案
1. 核对静态资源存放路径
SpringBoot默认识别的静态资源目录为:
src/main/resources/staticsrc/main/resources/publicsrc/main/resources/resourcessrc/main/resources/META-INF/resources
将2.jpg放入上述任意目录(推荐static),访问路径直接用http://localhost:8080/2.jpg即可,无需添加目录前缀。
2. 检查静态资源配置是否正确
若修改过配置文件,确保参数无误:
application.properties 示例:
# 允许所有请求匹配静态资源 spring.mvc.static-path-pattern=/** # 指定静态资源存放位置,默认值如下,自定义时要保证路径正确 spring.web.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
application.yml 示例:
spring: mvc: static-path-pattern: /** web: resources: static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
注意不要将static-path-pattern设为/static/**,除非访问时手动添加/static/前缀。
3. 排查自定义WebMvcConfigurer的影响
如果自定义了WebMvcConfigurer,需确保addResourceHandlers方法正确配置静态资源映射:
@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 映射classpath下的静态资源 registry.addResourceHandler("/**") .addResourceLocations("classpath:/static/", "classpath:/public/"); // 若需映射本地磁盘资源,可添加以下配置 // registry.addResourceHandler("/**").addResourceLocations("file:D:/local-images/"); } }
避免重写其他方法时破坏默认的静态资源匹配规则。
4. 排除拦截器/过滤器对静态资源的拦截
若项目中有自定义拦截器,需排除静态资源路径:
@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyCustomInterceptor()) .addPathPatterns("/**") .excludePathPatterns("/**.jpg", "/**.png", "/**.css", "/**.js"); }
过滤器同理,需确保静态资源请求不会被拦截过滤。
5. 确认打包后资源是否存在
若以jar包运行,打开jar包检查BOOT-INF/classes/static/下是否有2.jpg。若缺失,需调整打包配置:
Maven pom.xml 示例:
<build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*</include> </includes> </resource> </resources> </build>
内容的提问来源于stack exchange,提问作者n0thing1993
相关产品推荐
相关产品推荐

