如何在 Thymeleaf 模板中动态设置页面的 title、description 和 keywords?

解读

国内面试官问这道题,表面看是“把三个 meta 标签写活”,实质在考察三层能力:

  1. 对 Thymeleaf 变量作用域与解析顺序的掌握(request < session < servletContext < Spring Bean)
  2. 对 Spring Boot 统一 SEO 字段建模的习惯(是各自散在 VO 里,还是收敛到 PageMetaDTO)
  3. 对“所见即所得”自然模板的理解——静态原型打开时不报错,上线后又能瞬间替换文案,方便运营与 SEO 同学二次编辑。

如果候选人只回答“用 th:text 就行”,会被追问“运营临时改关键词是否必须重启”“中英文站点怎么切换”“列表页和详情页字段冲突怎么办”。因此答案必须覆盖:数据来源 → 回退策略 → 国际化 → 性能兜底 → 前后端协作规范。

知识点

  1. Thymeleaf 变量解析优先级:#request → #session → #servletContext → Spring Bean;可借助 @ControllerAdvice 统一向 Model 添加属性,避免每个接口重复 set。
  2. 自然模板原则:使用 th:utext 或 th:text 时,保证原型打开不出现“??”占位;推荐 th:utext="seo.title"+原型默认值,例如<titleth:utext="{seo.title}" + 原型默认值,例如 <title th:utext="{seo.title}">默认标题</title>。
  3. 国际化:配合 #{...} 消息表达式,如 th:utext="${seo.title} ?: #{seo.default.title}",实现中英文关键词一键切换。
  4. 片段复用:使用 layout:fragment 或 th:replace 把 head 区域抽成公共片段,确保全站 meta 结构一致。
  5. SEO 运营兜底:当后端字段为空时,自动拼接“站点名-频道名”作为 title,防止搜索引擎抓取到空白或重复标题。
  6. 安全与性能:禁用 th:utext 直接输出用户富文本,防止 XSS;对关键词列表使用内联 JS 预加载时,加 th:inline="none" 避免表达式泄露。

答案

步骤一:在 Spring Boot 中定义通用的 SEO 数据模型

public class SeoAttributes {
    private String title;
    private String description;
    private String keywords;
    // getter/setter 省略
}

步骤二:使用 @ControllerAdvice 统一注入

@ControllerAdvice
public class SeoAdvice {
    @ModelAttribute("seo")
    public SeoAttributes defaultSeo() {
        SeoAttributes s = new SeoAttributes();
        s.setTitle("默认站点标题");
        s.setDescription("默认描述");
        s.setKeywords("默认关键词");
        return s;
    }
}

步骤三:在 Thymeleaf 模板 head 片段中动态替换

<head th:fragment="commonHead">
    <title th:utext="${seo.title}">默认站点标题</title>
    <meta name="description" th:content="${seo.description}">
    <meta name="keywords" th:content="${seo.keywords}">
</head>

步骤四:具体页面覆盖

@GetMapping("/product/{id}")
public String detail(@PathVariable Long id, Model model) {
    Product p = service.find(id);
    SeoAttributes seo = new SeoAttributes();
    seo.setTitle(p.getName() + "-官方商城");
    seo.setDescription(p.getSubTitle());
    seo.setKeywords(String.join(",", p.getTags()));
    model.addAttribute("seo", seo);
    return "product/detail";
}

步骤五:国际化站点切换

<meta name="keywords" th:content="${seo.keywords} ?: #{seo.product.keywords}">

配合 messages.properties 中的

seo.product.keywords=手机,数码,正品

即可实现中英文关键词无重启切换。

步骤六:运营兜底策略

if(StringUtils.isBlank(seo.getTitle())){
    seo.setTitle("频道名-站点名");
}

防止空标题被搜索引擎降权。

通过以上六步,title、description、keywords 完全由后端动态注入,静态原型可正常打开,运营同学只需改数据库或 CMS 即可实时生效,无需重启应用。

拓展思考

  1. 大型站点往往有几十万详情页,关键词需要结合实时热词。可在 SeoAdvice 中注入 Redis 缓存的热词服务,定时刷新,Thymeleaf 侧零改动。
  2. 为了支持社交媒体分享,title/description 同时需要写入 Open Graph 和 Twitter Card 标签,思路一致,只是字段名不同,建议再扩展一个 OgAttributes,统一在 commonHead 片段输出。
  3. 如果页面采用服务端渲染 + 客户端路由的混合模式(如 Vue 嵌在 Thymeleaf 内),需要保留一份“首屏 meta”由 Thymeleaf 输出,后续路由切换通过 JS 改 document.title,避免爬虫只抓到首屏标题。
  4. 对于需要投放百度/微信广告的场景,关键词字段常被渠道强制校验,可在 SeoAttributes 里加 Map<String,String> extendMeta,通过 th:each 动态生成任意 meta,避免频繁改模板。
  5. 最后,面试时可以反问面试官:贵司运营改 SEO 字段的频次如何?是否有独立的 CMS 系统?根据答案决定是用数据库、配置中心还是消息队列来驱动 Thymeleaf 刷新,从而体现你对业务与技术结合的深度思考。