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

使用Thymeleaf实现Spring MVC主题切换时CSS加载失败问题

Spring MVC + Thymeleaf 主题切换失效问题

问题描述

参考Spring MVC主题切换方案,改用Thymeleaf替代JSP实现主题切换,但应用切换主题后样式无变化。尝试将JSP的<spring:theme code='styleSheet'/>转换为Thymeleaf表达式,仅th:href="${@environment.getProperty('stylesheet')}"能解析值,但页面仍未加载对应CSS,浏览器检查元素显示CSS文件未正确引入。

相关代码示例

配置类 ThemeConfig

@Configuration
public class ThemeConfig implements WebMvcConfigurer {
    @Bean
    public ThemeResolver themeResolver() {
        CookieThemeResolver themeResolver = new CookieThemeResolver();
        themeResolver.setDefaultThemeName("light");
        return themeResolver;
    }
    @Bean
    public ThemeChangeInterceptor themeChangeInterceptor() {
        ThemeChangeInterceptor interceptor = new ThemeChangeInterceptor();
        interceptor.setParamName("theme");
        return interceptor;
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(themeChangeInterceptor());
    }
}

HTML页面代码

<head>
...
<link rel="stylesheet" type="text/css" th:href="${@environment.getProperty('stylesheet')}">
...
</head>
<body>
...
    <div class="dropdown-container ms-4">
        <a th:href="@{?theme=dark}">[[#{dashboard.theme-dark}]]</a>
        <a th:href="@{?theme=light}">[[#{dashboard.theme-light}]]</a>
        <a th:href="@{?theme=blue}">[[#{dashboard.theme-blue}]]</a>
    </div>
...</body>

主题属性文件 dark.properties(已尝试多种路径写法)

stylesheet=/css/themes/dark.css
background=black

主题CSS文件 dark.css

footer{
    height: 100px;
    background-color: red;
}

文件结构说明

  • CSS文件结构:CSS文件结构
  • 主题属性文件结构:主题属性文件结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 00:50:39