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

Spring Boot打包Jar后Thymeleaf公共头部无法加载问题求助

解决Spring Boot打包Jar后Thymeleaf片段无法加载的问题

检查路径大小写一致性

Jar包基于类Unix文件系统,对路径大小写敏感,而本地Windows开发环境不敏感。确认你的引用路径fragments/header和实际文件路径src/main/resources/templates/fragments/header.html的大小写完全匹配,避免出现Fragments/Header与引用路径大小写不一致的情况。

简化片段引用语法

尝试移除表达式包裹符~{},直接使用如下引用方式:

<div th:replace="fragments/header :: common-header"></div>

部分场景下,Thymeleaf在Jar环境中对表达式语法的解析存在细微差异,简化后可解决加载问题。

确认资源文件已被正确打包

用解压工具打开打包后的Jar包,检查BOOT-INF/classes/templates/fragments/header.html是否存在且内容完整:

  • 若文件缺失,检查Maven的pom.xml配置,确保templates目录被包含:
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*</include>
            </includes>
        </resource>
    </resources>
    
  • Gradle项目则确认sourceSets配置正确:
    sourceSets {
        main {
            resources {
                srcDirs = ['src/main/resources']
            }
        }
    }
    

清理缓存后重新打包

本地开发缓存可能干扰打包结果,执行清理命令后重新打包:

  • Maven:mvn clean package
  • Gradle:./gradlew clean build

检查Thymeleaf配置

确认application.properties/application.yml中的Thymeleaf配置无异常:

spring.thymeleaf.cache=false # 调试时关闭缓存,生产环境可设为true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

确保prefix为classpath:/templates/,保证Jar中的模板文件能被正确定位。

验证片段定义正确性

打开header.html,确认common-header片段的语法无错误:

<div th:fragment="common-header">
    <!-- 头部内容 -->
</div>

避免片段标签嵌套错误或语法疏漏,本地缓存可能掩盖这类问题,打包后会暴露出来。

内容的提问来源于stack exchange,提问作者kala-alt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 21:42:09