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

Java Spring中访问JS/CSS文件出现404错误的求助

解决Spring Boot + Thymeleaf引入静态JS文件失效问题

核心问题分析

你的技术栈包含Spring Security 6.1.5和Atlassian Connect Spring Boot 4.0.5,这两个组件是导致静态资源无法访问的主要潜在原因:

  1. Spring Security默认会拦截所有HTTP请求,包括静态资源路径
  2. Atlassian Connect有自身的请求路由和资源处理逻辑,可能覆盖了Spring Boot默认的静态资源规则

有效解决方案

1. 配置Spring Security放行静态资源

在Spring Security配置类中,添加对/js/**路径的放行规则,避免安全框架拦截静态资源请求:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            // 保留你的其他安全配置
            .authorizeHttpRequests(auth -> auth
                // 放行所有静态资源路径
                .requestMatchers("/js/**", "/css/**", "/images/**").permitAll()
                // 其他请求的授权规则
                .anyRequest().authenticated()
            );
        return http.build();
    }
}

2. 移除冗余的静态资源配置

Spring Boot 3.x已默认将classpath:/static/作为静态资源根目录,你之前添加的额外配置反而可能引发冲突,建议:

  • 删除spring-mvc.xml文件
  • 简化WebMvcConfig,确保拦截器不干扰静态资源:
    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer {
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new RequestsInterceptor())
                // 排除静态资源路径,避免拦截器拦截
                .excludePathPatterns("/js/**");
        }
    }
    
  • 恢复application.yml的默认配置,删除你添加的spring.web.resources节点

3. 适配Atlassian Connect的路径规则

Atlassian Connect Spring Boot会为应用添加默认路径前缀(通常为/connect),需确认资源引用是否匹配:

  • 如果应用作为Atlassian插件运行,调整Thymeleaf中的资源引用:
    <script th:src="@{/connect/js/file.min.js}" charset="UTF-8" type="text/javascript"></script>
    
  • 或在application.yml中自定义Connect上下文路径:
    atlassian:
      connect:
        context-path: /your-custom-path
    

4. 验证静态资源的直接访问性

启动应用后,直接访问http://localhost:8080/js/file.min.js(根据你的端口和上下文调整):

  • 若能正常下载JS文件,说明资源配置正常,问题出在Thymeleaf引用或Spring Security拦截
  • 若返回404,检查:
    • JS文件是否确实在src/main/resources/static/js/目录下
    • 打包后的jar/war中是否包含该文件(可解压验证)
    • 应用启动日志是否有静态资源加载报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 06:55:14