如何将常用组件(如分页器、搜索栏)抽象为可复用的 Thymeleaf 片段?
解读
在国内 Spring Boot + Thymeleaf 的主流技术栈里,面试官真正想考察的是“你是否能把前后端协作的痛点——重复 HTML、硬编码参数、国际化、SEO、工具识别——一次性解决”。
他们希望听到:
- 用
th:fragment定义语义化片段,保证“自然模板”能在浏览器直接打开; - 用
th:replace/th:insert调用,支持“参数默认值 + 运行时覆盖”两种模式; - 用
~{ ::selector}语法实现“片段内再片段”,解决分页器内部排序图标、搜索栏内部下拉框的嵌套复用; - 用 Spring MessageSource 完成国际化,而不是把中文硬写在片段里;
- 用
th:classappend与th:styleappend保证片段在 Tailwind / Bootstrap 等多主题场景下“零改动”; - 用
th:with在调用侧生成一次性变量,避免把计算逻辑污染到片段内部; - 用
th:assert做编译期参数校验,把 NPE 提前到渲染阶段; - 用 Maven 多模块把片段打成
META-INF/templates/fragments包,让公司级组件库可以“依赖即引用”; - 用
layout:decorate与th:remove="tag"兼顾 SEO 与原型评审,让设计小姐姐用 Axure 打开也能看。
一句话:片段不是“抠一块 HTML”,而是“可配置、可国际化、可主题化、可嵌套、可打包、可断言”的完整组件体系。
知识点
- 片段定义:
th:fragment="pagination (pageUrl, current, total, showPrevNext)" - 片段调用:
~{ fragments/pagination :: pagination (pageUrl=${@environment.getProperty('app.ctx')}+'/user/list', current=${page.number}, total=${page.totalPages})} - 默认值:
th:fragment="searchBar (placeholder=#{search.default})" - 嵌套片段:分页器内部把“上一页”箭头再拆成
th:fragment="navIcon (direction)" - 国际化:
th:text="#{pagination.page(${current},${total})}" - 主题化:
th:classappend="${theme != null ? 'ui-'+theme : ''}" - 编译期断言:
th:assert="${!#strings.isEmpty(pageUrl)}" - 变量作用域:
th:with="start=${current-2}, end=${current+2}" - 包级复用:把片段放到
common-starter模块的META-INF/resources/templates/fragments/目录,其他项目直接~{ /META-INF/... }引用 - 性能:片段开启
spring.thymeleaf.cache=true,上线后零解析开销
答案
下面给出一套可直接落地的“分页器 + 搜索栏”双组件示例,覆盖上面全部知识点,面试官可以逐行追问。
- 目录结构(符合国内阿里规约)
src/
└── resources/
├── templates/
│ ├── fragments/
│ │ ├── component/
│ │ │ ├── pagination.html
│ │ │ └── searchBar.html
│ └── demo/
│ └── user-list.html
└── i18n/
└── messages.properties
- 分页器片段
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>
- 搜索栏片段
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>
- 业务页面
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>
- 国际化文件
messages.properties
search.default=请输入关键词
search.btn=搜索
pagination.total=共 {0} 页
- 打包复用(公司级starter)
把
fragments目录放到common-thymeleaf-spring-boot-starter的META-INF/resources/templates/下,其他项目引入依赖后,直接:
<div th:replace="~{/META-INF/resources/templates/fragments/component/pagination :: pagination(...)}"/>
即可。至此,组件完全抽象,符合国内“中台化”思想。
拓展思考
-
如果分页数据是异步接口,如何保持同一套片段?
答:用th:fragment定义“纯 HTML”版本,再写一段可选的th:inline="javascript"片段,把总页数、当前页注入 window.__page 变量,前端 Vue/React 拿到后复用同一套 CSS,实现“服务端首屏 + 客户端翻页”同构。 -
片段参数越来越多,是否违背“单一职责”?
答:把片段拆成“布局片段”与“数据片段”,布局片段只关心 HTML 结构,数据片段用th:insert注入,参考“复合组件模式”,国内阿里内部叫“容器 + 插件”。 -
如何对片段做单元测试?
答:用 Spring Boot 2.5+ 提供的@WebMvcTest+MockMvc+ThymeleafTesting模板引擎独立启动,只渲染片段,断言输出 HTML 是否包含特定 class,避免把测试跑到整个页面层。 -
片段缓存与热更新如何平衡?
答:线上开启spring.thymeleaf.cache=true,开发阶段用spring-boot-devtools的 restart 触发TemplateEngine.clearTemplateCache(),或者把片段放到 Redis,版本号变化时清缓存,兼顾性能与敏捷。 -
多主题场景下,如何做到“不改 Java 代码,只换皮肤包”?
答:把主题资源放到classpath:/theme/{name}/fragments/,通过ThemeResolver切换主题名,片段里用~{theme/{themeName}/fragments/pagination :: pagination}动态解析,实现“换肤即换包”,满足国内运营商、政府、金融等多套 VI 需求。