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

Java 8 Spring Boot WebSocket服务无法渲染Static目录下的index.html

解决方案

1. 确认静态文件目录结构

Spring Boot默认会扫描以下目录作为静态资源目录(优先级从高到低):

  • src/main/resources/META-INF/resources/
  • src/main/resources/resources/
  • src/main/resources/static/
  • src/main/resources/public/

把你的index.html放在src/main/resources/static/下,保证目录结构如下:

src/
└── main/
    └── resources/
        └── static/
            ├── index.html
            ├── js/
            │   └── app.js
            └── css/
                └── style.css

2. 检查自定义WebMvc配置是否覆盖默认规则

如果项目里有实现WebMvcConfigurer或继承WebMvcConfigurationSupport的配置类,可能会冲掉Spring Boot默认的静态资源映射。

要是你继承了WebMvcConfigurationSupport,要么改成实现WebMvcConfigurer,要么手动添加静态资源映射:

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

3. 排查拦截器/过滤器的拦截规则

如果项目里配置了拦截器或过滤器,要确保它们不拦截静态资源请求。比如在拦截器里排除静态资源路径:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CustomInterceptor())
                .excludePathPatterns("/**/*.html", "/**/*.js", "/**/*.css");
    }
}

4. 配置默认首页(可选)

如果想访问根路径/时直接返回index.html,可以在application.properties里加配置:

spring.mvc.static-path-pattern=/**
spring.web.resources.static-locations=classpath:/static/
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.html

或者用代码配置:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
    }
}

5. 清理构建缓存并重启

有时候IDE缓存或旧构建产物会导致静态资源加载失败,执行以下操作:

  • 执行mvn clean(Maven项目)或gradle clean(Gradle项目)清理构建缓存
  • 重启IDE后重新构建项目
  • 用Ctrl+Shift+R强制刷新浏览器,清除浏览器缓存

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 09:57:18