如何将常用组件(如分页器、搜索栏)抽象为可复用的 Thymeleaf 片段?

解读

在国内 Spring Boot + Thymeleaf 的主流技术栈里,面试官真正想考察的是“你是否能把前后端协作的痛点——重复 HTML、硬编码参数、国际化、SEO、工具识别——一次性解决”。
他们希望听到:

  1. 用 th:fragment 定义语义化片段,保证“自然模板”能在浏览器直接打开;
  2. 用 th:replace / th:insert 调用,支持“参数默认值 + 运行时覆盖”两种模式;
  3. 用 ~{ ::selector} 语法实现“片段内再片段”,解决分页器内部排序图标、搜索栏内部下拉框的嵌套复用;
  4. 用 Spring MessageSource 完成国际化,而不是把中文硬写在片段里;
  5. 用 th:classappend 与 th:styleappend 保证片段在 Tailwind / Bootstrap 等多主题场景下“零改动”;
  6. 用 th:with 在调用侧生成一次性变量,避免把计算逻辑污染到片段内部;
  7. 用 th:assert 做编译期参数校验,把 NPE 提前到渲染阶段;
  8. 用 Maven 多模块把片段打成 META-INF/templates/fragments 包,让公司级组件库可以“依赖即引用”;
  9. 用 layout:decorate 与 th:remove="tag" 兼顾 SEO 与原型评审,让设计小姐姐用 Axure 打开也能看。

一句话:片段不是“抠一块 HTML”,而是“可配置、可国际化、可主题化、可嵌套、可打包、可断言”的完整组件体系。

知识点

  1. 片段定义:th:fragment="pagination (pageUrl, current, total, showPrevNext)"
  2. 片段调用:~{ fragments/pagination :: pagination (pageUrl=${@environment.getProperty('app.ctx')}+'/user/list', current=${page.number}, total=${page.totalPages})}
  3. 默认值:th:fragment="searchBar (placeholder=#{search.default})"
  4. 嵌套片段:分页器内部把“上一页”箭头再拆成 th:fragment="navIcon (direction)"
  5. 国际化:th:text="#{pagination.page(${current},${total})}"
  6. 主题化:th:classappend="${theme != null ? 'ui-'+theme : ''}"
  7. 编译期断言:th:assert="${!#strings.isEmpty(pageUrl)}"
  8. 变量作用域:th:with="start=${current-2}, end=${current+2}"
  9. 包级复用:把片段放到 common-starter 模块的 META-INF/resources/templates/fragments/ 目录,其他项目直接 ~{ /META-INF/... } 引用
  10. 性能:片段开启 spring.thymeleaf.cache=true,上线后零解析开销

答案

下面给出一套可直接落地的“分页器 + 搜索栏”双组件示例,覆盖上面全部知识点,面试官可以逐行追问。

  1. 目录结构(符合国内阿里规约)
src/
└── resources/
    ├── templates/
    │   ├── fragments/
    │   │   ├── component/
    │   │   │   ├── pagination.html
    │   │   │   └── searchBar.html
    │   └── demo/
    │       └── user-list.html
    └── i18n/
        └── messages.properties
  1. 分页器片段 pagination.html(自然模板,浏览器可直接打开)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<!-- ① 语义化命名 + 参数列表 + 默认值 -->
<th:block th:fragment="pagination (pageUrl, current, total, showPrevNext=true)"
          th:assert="${!#strings.isEmpty(pageUrl)}">

    <!-- ② 内部变量,避免片段被污染 -->
    <th:block th:with="start=${T(java.lang.Math).max(1, current-2)},
                       end=${T(java.lang.Math).min(total, current+2)}">

        <nav th:classappend="${theme != null ? 'ui-'+theme : ''}"
             class="pagination-wrapper">
            <ul class="pagination">
                <!-- ③ 嵌套片段:上一页图标 -->
                <li th:if="${showPrevNext and current > 1}"
                    th:replace="~{fragments/component/pagination :: navIcon('prev', ${pageUrl}, ${current-1})}"></li>

                <!-- ④ 数字页码 -->
                <li th:each="i : ${#numbers.sequence(start, end)}"
                    th:classappend="${i == current ? 'active' : ''}">
                    <a th:href="@{${pageUrl}(page=${i-1})}" th:text="${i}">1</a>
                </li>

                <!-- 下一页图标 -->
                <li th:if="${showPrevNext and current < total}"
                    th:replace="~{fragments/component/pagination :: navIcon('next', ${pageUrl}, ${current+1})}"></li>
            </ul>
            <!-- ⑤ 国际化 -->
            <span th:text="#{pagination.total(${total})}">共 0 页</span>
        </nav>
    </th:block>
</th:block>

<!-- ⑥ 内部嵌套片段:箭头图标 -->
<th:block th:fragment="navIcon (direction, url, pageNum)">
    <a th:href="@{${url}(page=${pageNum-1})}"
       th:aria-label="${direction == 'prev' ? '上一页' : '下一页'}">
        <i th:class="${direction == 'prev' ? 'icon-arrow-left' : 'icon-arrow-right'}"></i>
    </a>
</th:block>
</body>
</html>
  1. 搜索栏片段 searchBar.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<th:block th:fragment="searchBar (action, method='get', placeholder=#{search.default}, buttonText=#{search.btn})">
    <form th:action="${action}" th:method="${method}" class="search-bar">
        <input type="text" name="keyword" th:placeholder="${placeholder}" class="input-keyword"/>
        <button type="submit" th:text="${buttonText}">搜索</button>
    </form>
</th:block>
</body>
</html>
  1. 业务页面 user-list.html(演示如何调用)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>用户列表</title></head>
<body>
<!-- ① 搜索栏:只传必要参数,其余走默认值 -->
<div th:replace="~{fragments/component/searchBar :: searchBar (action=@{/user/list})}"></div>

<!-- ② 分页器:全参数覆盖,支持主题 -->
<div th:replace="~{fragments/component/pagination :: pagination (
        pageUrl=${@environment.getProperty('app.ctx')}+'/user/list',
        current=${page.number},
        total=${page.totalPages},
        showPrevNext=true,
        theme='bootstrap')}"></div>
</body>
</html>
  1. 国际化文件 messages.properties
search.default=请输入关键词
search.btn=搜索
pagination.total=共 {0} 页
  1. 打包复用(公司级starter) 把 fragments 目录放到 common-thymeleaf-spring-boot-starter 的 META-INF/resources/templates/ 下,其他项目引入依赖后,直接:
<div th:replace="~{/META-INF/resources/templates/fragments/component/pagination :: pagination(...)}"/>

即可。至此,组件完全抽象,符合国内“中台化”思想。

拓展思考

  1. 如果分页数据是异步接口,如何保持同一套片段?
    答:用 th:fragment 定义“纯 HTML”版本,再写一段可选的 th:inline="javascript" 片段,把总页数、当前页注入 window.__page 变量,前端 Vue/React 拿到后复用同一套 CSS,实现“服务端首屏 + 客户端翻页”同构。

  2. 片段参数越来越多,是否违背“单一职责”?
    答:把片段拆成“布局片段”与“数据片段”,布局片段只关心 HTML 结构,数据片段用 th:insert 注入,参考“复合组件模式”,国内阿里内部叫“容器 + 插件”。

  3. 如何对片段做单元测试?
    答:用 Spring Boot 2.5+ 提供的 @WebMvcTest + MockMvc + ThymeleafTesting 模板引擎独立启动,只渲染片段,断言输出 HTML 是否包含特定 class,避免把测试跑到整个页面层。

  4. 片段缓存与热更新如何平衡?
    答:线上开启 spring.thymeleaf.cache=true,开发阶段用 spring-boot-devtools 的 restart 触发 TemplateEngine.clearTemplateCache(),或者把片段放到 Redis,版本号变化时清缓存,兼顾性能与敏捷。

  5. 多主题场景下,如何做到“不改 Java 代码,只换皮肤包”?
    答:把主题资源放到 classpath:/theme/{name}/fragments/,通过 ThemeResolver 切换主题名,片段里用 ~{theme/{themeName}/fragments/pagination :: pagination} 动态解析,实现“换肤即换包”,满足国内运营商、政府、金融等多套 VI 需求。