1. 概述

本文将介绍如何在 Thymeleaf 模板引擎中处理数组。为了快速搭建环境,我们会使用 Spring Boot 初始化工具来创建项目。

如果你对 Spring MVC 和 Thymeleaf 的基础还不熟悉,可以先参考 Spring MVC 中的 Thymeleaf 入门

2. Thymeleaf 依赖

pom.xml 中,我们只需要引入 Spring Web 和 Thymeleaf 的 Starter 依赖即可:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

✅ 加上这两个依赖后,Spring Boot 会自动配置 Thymeleaf,视图模板默认放在 src/main/resources/templates 目录下。

3. 控制器实现

为了简化演示,我们只写一个处理 GET 请求的接口:

@Controller
public class ThymeleafArrayController {
 
    @GetMapping("/arrays")
    public String arrayController(Model model) {
        String[] continents = {
          "Africa", "Antarctica", "Asia", "Australia", 
          "Europe", "North America", "South America"
        };
        
        model.addAttribute("continents", continents);

        return "continents";
    }
}

⚠️ 注意:原文拼错了 "Sourth America",已修正为 "South America"。这种低级错误在实际开发中很容易被忽略,建议上线前用静态检查工具扫一遍。

这个接口把一个字符串数组 continents 放进 Model,名字叫 "continents",这样在前端模板里就能通过这个名字访问它。

4. 视图模板使用

在 Thymeleaf 模板中,我们可以通过 ${continents} 获取控制器传来的数组。

4.1. 数组属性与索引访问

首先,我们可以获取数组长度:

<p>世界上有 <span th:text="${continents.length}"></span> 个大洲</p>

th:text 用于动态渲染文本内容,${} 中写的是 Spring EL 表达式。

和 Java 一样,我们也可以通过索引访问数组元素:

<ol>
    <li th:text="${continents[2]}"></li>
    <li th:text="${continents[0]}"></li>
    <li th:text="${continents[4]}"></li>
    <li th:text="${continents[5]}"></li>
    <li th:text="${continents[6]}"></li>
    <li th:text="${continents[3]}"></li>
    <li th:text="${continents[1]}"></li>
</ol>

输出结果就是按索引顺序列出各个大洲名称。这种写法适合静态展示少量数据,但如果数组很长,手动写索引就太傻了。

4.2. 遍历数组

更常用的方式是使用 th:each 进行循环遍历:

<ul th:each="continent : ${continents}">
    <li th:text="${continent}"></li>
</ul>

th:each 是 Thymeleaf 的核心迭代语法,格式为:

<element th:each="item : ${collection}">

其中 item 是当前元素的变量名,collection 是模型中的集合或数组。

❌ 踩坑提醒:上面代码里有个拼写错误 —— continet 少了个 n,但后面却用了 continent,会导致页面空白。Thymeleaf 不报错但渲染失败,调试起来很头疼。

我们也可以用其他标签做遍历,比如:

<h4 th:each="continent : ${continents}" th:text="${continent}"></h4>

每个大洲会单独显示在一个 <h4> 标题里。这说明 th:each 不局限于 <ul><ol>,任何能显示文本的标签都能用。

4.3. 数组工具方法

Thymeleaf 提供了 #arrays 工具类,封装了一些常用操作:

  • 获取长度:
<p>共有 <span th:text="${#arrays.length(continents)}"></span> 个大洲</p>
  • 判断是否包含某个元素:
<p>Europe 是大洲吗?<span th:text="${#arrays.contains(continents, 'Europe')}"></span></p>

输出为 true

  • 判断是否为空:
<p>大洲数组为空?<span th:text="${#arrays.isEmpty(continents)}"></span></p>

输出为 false

✅ 常用 #arrays 方法总结:

方法 说明
#arrays.length(arr) 返回数组长度
#arrays.contains(arr, elem) 是否包含某元素
#arrays.isEmpty(arr) 是否为空数组
#arrays.toArray(list) 转换为数组(List → Array)

这些工具类方法在处理复杂逻辑时非常实用,避免在 Controller 层做太多数据预处理。

4.4. List 工具方法(兼容数组)

除了 #arrays,Thymeleaf 还提供了 #lists 工具类,它的 #lists.size() 不仅适用于 List,也支持 Array

举个例子,我们新增一个控制器:

@Controller
@RequestMapping("/lists")
public class ListsController {

    @GetMapping("/size")
    public String usingSize(Model model) {
        model.addAttribute("myList", getColors());
        return "lists/size";
    }

    private List<String> getColors() {
        return Arrays.asList("Red", "Green", "Blue", "Yellow");
    }
}

模板中使用:

<p>颜色数量:<span th:text="${#lists.size(myList)}"></span></p>

✅ 输出为 4

⚠️ 注意:#lists.size() 要求传入的对象必须是非 null。如果不确定,需要先判空:

<p th:if="${myList != null}" th:text="${#lists.size(myList)}">List Size</p>
<p th:if="${myList == null}">List is Null</p>

否则会抛出异常。

我们也可以用单元测试验证:

@Test
public void whenCalledSize_ThenReturnsSize() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.get("/lists/size"))
      .andExpect(status().isOk())
      .andExpect(content().string(containsString("颜色数量:<span>4</span>")));
}

✅ 建议:对于可能为空的集合,统一在 Controller 层初始化为 Collections.emptyList(),避免模板层频繁判空,代码更干净。

5. 总结

本文演示了在 Thymeleaf 中处理数组的几种方式:

  • ✅ 使用 ${array[index]} 按索引访问元素
  • ✅ 使用 th:each 遍历数组,支持任意 HTML 标签
  • ✅ 利用 #arrays 工具类获取长度、判断包含、判空等
  • #lists.size() 兼容数组和 List,但需注意 null 安全

📌 小贴士:虽然数组也能用,但在实际开发中更推荐传 List 给模板。因为 List 更灵活,且 Java 8+ 的 Arrays.asList()Stream.collect() 默认返回 List,与 Thymeleaf 集成更自然。

掌握这些技巧后,你就能轻松在前端模板中处理后端传来的数据了。


原始标题:Working With Arrays in Thymeleaf | Baeldung