You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot项目无法加载根目录下index.html的解决方案咨询

解决Spring Boot加载项目根目录下index.html的问题

我之前刚好处理过类似的需求,Spring Boot默认不会扫描项目根目录(和src同级的那个目录)作为静态资源路径,所以直接放那肯定找不到。下面给你两种可行的解决办法:

方法一:通过配置文件扩展静态资源位置

最直接的方式就是在配置文件里把项目根目录添加到Spring Boot的静态资源扫描列表中。

用application.properties配置:

# 把项目根目录(file:./)加到扫描列表,可按需求调整优先级
spring.web.resources.static-locations=file:./,classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

这里的file:./指向的是项目运行时的工作目录:IDE中运行时默认就是项目根目录,Jar包运行时就是你执行java -jar命令所在的目录,只要你的index.html在这个目录下就能被识别。

用application.yml配置:

spring:
  web:
    resources:
      static-locations:
        - file:./
        - classpath:/META-INF/resources/
        - classpath:/resources/
        - classpath:/static/
        - classpath:/public/

配置完成后,你在Rest Controller里返回"/index.html"就能正常访问到根目录下的文件了。

方法二:自定义资源处理器(更精准控制)

如果不需要扫描整个根目录,只想单独映射index.html,或者有其他定制化需求,可以写一个配置类实现WebMvcConfigurer:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CustomResourceConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 只映射根目录下的index.html
        registry.addResourceHandler("/index.html")
                .addResourceLocations("file:./index.html");
        
        // 如果需要映射根目录下所有静态资源,可以替换成下面这段:
        // registry.addResourceHandler("/**")
        //         .addResourceLocations("file:./");
    }
}

这种方式的好处是不会干扰Spring Boot默认的静态资源路径,只处理你指定的资源。

小提醒

  • 如果你用Jar包部署,记得把index.html和Jar包放在同一个目录下(或者你执行java -jar的目录),不然会找不到。
  • IDE中运行的话,直接把index.html放在项目根目录(和src、pom.xml同级)就没问题。

内容的提问来源于stack exchange,提问作者Swanand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:39:15