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

Spring Boot+Thymeleaf项目CSS/JS加载失败:MIME类型错误求助

问题解决:Spring Boot静态资源加载失败(MIME类型错误)

核心问题分析

你遇到的CSS/JS加载失败、MIME类型错误的问题,根源在于两个关键点:

  1. 静态资源引用路径错误:使用相对路径../static/xxx导致请求被路由到登录页面控制器,返回HTML而非静态资源
  2. Spring Security拦截静态资源:所有请求都被要求认证,静态资源请求被拦截后重定向到登录页,返回HTML内容

具体修复步骤

1. 修正Thymeleaf页面中的静态资源引用

Spring Boot默认会将src/main/resources/static/目录下的资源映射到根路径/,因此不需要在路径中包含static。改用Thymeleaf的绝对路径语法@{},确保无论当前页面URL是什么,都能正确定位静态资源:

修改login-page.html的对应部分:

<head>
    <!-- ... 其他内容 ... -->
    <!-- 修正CSS引用 -->
    <link rel="stylesheet" th:href="@{/css/login-page.css}">
</head>
<body>
    <!-- ... 其他内容 ... -->
    <!-- 修正JS引用 -->
    <script type="text/javascript" th:src="@{/js/login-page.js}"></script>
    <!-- ... 其他第三方JS ... -->
</body>

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

在SecurityConfig中添加静态资源路径的放行规则,确保这些请求不需要认证就能访问:

@Configuration
@EnableWebSecurity
@PropertySource("classpath:application.properties")
public class SecurityConfig {

    @Value("${password-manager-base-url}")
    String baseUrl;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeHttpRequests(configurer->
                configurer
                        // 放行所有静态资源路径
                        .requestMatchers("/css/**", "/js/**", "/webjars/**").permitAll()
                        .anyRequest().authenticated()
        )
                .formLogin(form ->
                        form
                                .loginPage(baseUrl+"/login-page")
                                .loginProcessingUrl(baseUrl+"/authenticateUser")
                                .permitAll()
                )
                .logout(LogoutConfigurer::permitAll);
        return httpSecurity.build();
    }
}

3. 确保页面能获取到baseUrl参数

在PageController中将baseUrl传入模型,让Thymeleaf可以正确解析登录表单的提交路径:

@Controller
public class PageController {
    @Value("${password-manager-base-url}")
    String baseUrl;

    @GetMapping("${password-manager-base-url}/login-page")
    public String login(Model model) {
        model.addAttribute("baseUrl", baseUrl);
        return "login-page";
    }
}

错误原因补充说明

当你使用../static/css/login-page.css这种相对路径时,当前页面URL是/password-manager/login-page,浏览器实际请求的地址是/password-manager/static/css/login-page.css。这个路径没有对应的控制器处理,同时Spring Security会拦截未认证的请求,将其重定向到登录页,返回的是HTML内容。因此浏览器收到的响应MIME类型是text/html,而非预期的text/css或application/javascript,触发了严格MIME类型检查的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 23:17:41