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

Thymeleaf无法识别CSS文件问题排查与解决

Thymeleaf引入CSS样式不生效的问题与解决办法

问题现象

在Spring Boot项目中使用Thymeleaf模板引入CSS样式表后,页面样式完全不生效,控制台持续抛出静态资源找不到的警告:

2023-09-29T14:48:19.939+01:00  WARN 4772 --- [nio-8080-exec-7] o.s.web.servlet.PageNotFound             : No mapping for GET /static/css/main.css
2023-09-29T14:59:52.447+01:00  WARN 14708 --- [nio-8080-exec-7] o.s.web.servlet.PageNotFound             : No mapping for GET /css/main.css

相关代码与配置

Thymeleaf HTML代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Homepage</title>
    <link th:href="@{/css/main.css}" rel="stylesheet">
</head>
<body class="custom-bg">

<nav>
    <ul>
        <li>
            <a th:href="@{/admin/homepage}">
                Home
            </a>
        </li>
        <li>
            <a th:href="@{/welcome}">
                Page 1
            </a>
        </li>
        <li>
            <a th:href="@{/admin/new/employees}">
                Create New Employee
            </a>
        </li>
        <li>
            <form th:action="@{/logout}" method="post" >
                <button type="submit">Logout</button>
            </form>
        </li>
    </ul>
</nav>

<h1>Admin homepage</h1>
<h2>Welcome,</h2>
<h3 th:text="${employee.getFirstName()} + ' ' + ${employee.getLastName()}">Name</h3>

</body>
</html>

CSS文件内容

* {
    color: aqua;
}

.custom-bg {
    background-color: deeppink;
}

body {
    background-color: deeppink;
}

项目文件结构

CSS文件放置在src/main/resources/static/css/目录下,符合Spring Boot静态资源默认存放规范。

Spring Security配置

已在过滤链中放行静态资源路径,但问题未解决:

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

    http.authorizeHttpRequests(auth -> {
        auth.requestMatchers("/admin/**")
                .hasAuthority("ADMIN");
        auth.requestMatchers("/manager/**")
                .hasAuthority("MANAGER");
        auth.requestMatchers("/employee/**")
                .hasAuthority("EMPLOYEE");
        auth.requestMatchers("employees")
                .hasAnyAuthority("MANAGER", "EMPLOYEE");
        auth.requestMatchers("/css/**")
                        .permitAll();
        auth.requestMatchers("/js/**")
                .permitAll();
        auth.requestMatchers("/images/**")
                .permitAll();
        auth.anyRequest().authenticated();
    });

    http.httpBasic(Customizer.withDefaults());

    http.formLogin()
            .loginProcessingUrl("/login")
            .successHandler(loginSuccessHandler)
            .permitAll()
            .and()
            .logout()
            .deleteCookies("JSESSIONID");

    http.csrf((AbstractHttpConfigurer::disable));

    return http.build();
}

排查尝试

  • 按照Thymeleaf官方文档使用标准路径th:href="@{/css/main.css}",也尝试过相对路径th:href="@{../static/css/main.css}",IDE能正常识别文件,但页面加载时样式仍不生效
  • 排查Spring Security配置,确认已放行/css/**路径,但控制台仍报资源找不到

最终解决方案

添加自定义Controller映射,手动处理CSS资源的请求并返回正确的内容类型,解决了资源加载问题:

@GetMapping(value = "/css/{fileName:.+}", produces = "text/css")
public ResponseEntity<Resource> getCssFile(@PathVariable String fileName) {
    // 构造CSS文件路径
    String cssFilePath = "static/css/" + fileName;

    // 从classpath加载资源
    Resource resource = new ClassPathResource(cssFilePath);

    // 返回带有正确头部的响应
    return ResponseEntity.ok()
        .header("Content-Disposition", "inline")
        .body(resource);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:34:53