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

Thymeleaf片段无法显示求助(Spring Boot+IntelliJ环境)

Thymeleaf片段引用无内容显示问题排查与解决

问题描述

在IntelliJ Idea + Spring Boot环境下,使用th:fragment结合th:replace/th:insert时,页面无任何内容显示。已尝试修改引用路径、更换片段代码、添加/移除Thymeleaf命名空间、重启Tomcat,但问题依旧。

核心问题定位

你的index.html放在了src/main/resources/static目录下——这个目录是Spring Boot存放静态资源的位置,Thymeleaf引擎不会解析这里的文件,自然无法识别th:insert/th:replace这类Thymeleaf专属标签,导致片段无法加载。

解决步骤

  1. 调整文件位置
    将index.html从static目录移动到templates目录下,最终文件结构应为:

    project
    --src
    ----resources
    ------templates
    --------index.html
    --------fragments
    ----------test.html
    
  2. 修正片段引用路径
    由于test.html位于templates/fragments目录下,引用路径需改为:

    <div th:insert="fragments/test::test"></div>
    <div th:replace="fragments/test::test"></div>
    
  3. 规范片段文件(可选)
    在test.html中添加Thymeleaf命名空间,避免IDE语法警告(不影响功能,但更符合规范):

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <body>
        <div th:fragment="test">
          <h1>Hello from the fragment!</h1>
        </div>
    </body>
    </html>
    
  4. 重启应用
    直接运行Spring Boot主类即可,无需单独启动Tomcat(Spring Boot内置容器)。

验证效果

修改完成后访问应用根路径(如http://localhost:8080),页面会显示两次Hello from the fragment!,分别对应th:insert和th:replace的渲染效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:36:41