Spring Boot+Thymeleaf项目JS文件无法访问的问题排查
解决方案:Spring Boot+Thymeleaf JS文件404排查步骤
以下是针对你的问题的具体排查和解决方法:
1. 验证文件路径与大小写
首先确认你的文件结构完全符合预期:
- 确保JS文件的路径是
src/main/resources/static/js/createGraph.js(Maven/Gradle项目标准结构) - 注意文件名和文件夹名的大小写:Linux/macOS环境以及打包后的Jar包对路径大小写敏感,比如
JS文件夹和js会被视为不同路径,检查是否存在大小写不一致的问题
2. 检查构建后的资源文件
运行项目后,查看项目构建输出目录(Maven为target/classes/static/js,Gradle为build/resources/main/static/js):
- 如果
createGraph.js不存在,说明构建工具未正确复制该文件:- Maven项目:检查
pom.xml中的<resources>配置,确保没有排除.js文件,示例正确配置:<resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*</include> </includes> </resource> </resources> - Gradle项目:检查
build.gradle中的sourceSets配置,确保包含静态资源:sourceSets { main { resources { srcDirs = ['src/main/resources'] } } }
- Maven项目:检查
3. 排查拦截器/安全配置
- 自定义WebMvc配置:如果项目中有
WebMvcConfigurer实现,检查是否重写了addResourceHandlers方法,确保没有覆盖默认静态资源映射:@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 保留默认静态资源映射,或明确配置 registry.addResourceHandler("/**") .addResourceLocations("classpath:/static/"); } } - Spring Security配置:如果使用了Spring Security,必须允许静态资源的匿名访问,否则JS请求会被拦截:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/css/**", "/js/**", "/images/**").permitAll() .anyRequest().authenticated(); } }
4. 验证Thymeleaf标签写法
- 确保HTML根标签已引入Thymeleaf命名空间:
<html xmlns:th="http://www.thymeleaf.org"> - 简化script标签写法(HTML5中可省略
type="text/javascript"):<script th:src="@{/js/createGraph.js}"></script>
5. 清理缓存并重新构建
- 执行构建工具的清理命令:Maven运行
mvn clean install,Gradle运行gradle clean build - 重启IDE和项目,避免缓存导致的资源未更新问题
内容的提问来源于stack exchange,提问作者Ayibogan
相关产品推荐
相关产品推荐

