java springboot 项目中静态资源无法访问的问题

默认 resource/static 目录下的静态html文件无法访问,需要配置。

您可以在 Spring Boot 的配置类中添加以下内容来手动配置静态资源目录:

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

配置后确实可以访问了,但 swagger-ui.html 无法访问了

这种情况通常是因为你的 addResourceHandlers 方法覆盖了 Spring Boot 的默认设置,导致 Swagger UI 页面无法访问。默认情况下,Spring Boot 会自动将 classpath:/META-INF/resources/ 目录下的静态资源文件映射到 /webjars/**/swagger-ui.html 路径下。

所以,如果您需要自定义一些资源文件的映射路径,可以在 addResourceHandlers 方法中添加额外的资源路径,并将默认的配置也包含在内,如下所示:

复制代码
Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/public/")
                .addResourceLocations("classpath:/resources/")
                .addResourceLocations("classpath:/META-INF/resources/");
    }
}
复制代码

 

posted on   空明流光  阅读(1859)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示