如何用Thymeleaf遍历ArrayList并解决仅显示首个对象问题?
Hey Jill, let's work through your two questions step by step—they're super common when getting started with Thymeleaf, so you're not alone!
1. 如何使用Thymeleaf实现ArrayList的遍历展示?
Thymeleaf提供了th:each属性专门用来遍历集合(包括ArrayList),核心思路是在Controller里把集合存入Model,然后在HTML中用th:each指定遍历的集合和临时变量,渲染每个元素的属性。
第一步:Controller层准备数据
先确保你把ArrayList放到Model中,让Thymeleaf能访问到:
@GetMapping("/your-page") public String loadData(Model model) { // 假设你有一个自定义的实体类,比如Product,包含name、description等属性 List<Product> productList = new ArrayList<>(); productList.add(new Product("Wireless Headphones", "Noise-canceling over-ear design")); productList.add(new Product("Smart Watch", "Fitness tracking + heart rate monitor")); // 将集合存入Model,键名"products"会在HTML中用到 model.addAttribute("products", productList); return "your-template-name"; }
第二步:HTML层遍历渲染
在Thymeleaf模板中,把th:each添加到需要重复渲染的元素上(比如每行、每个卡片),示例如下:
<!-- 用列表展示 --> <ul> <!-- 遍历products集合,每个元素临时命名为product --> <li th:each="product : ${products}"> <h4 th:text="${product.name}"></h4> <p th:text="${product.description}"></p> </li> </ul> <!-- 用表格展示 --> <table border="1"> <tr> <th>Product Name</th> <th>Description</th> </tr> <!-- 每一行对应集合中的一个元素 --> <tr th:each="product : ${products}"> <td th:text="${product.name}"></td> <td th:text="${product.description}"></td> </tr> </table>
th:each="product : ${products}"的意思是:遍历名为products的集合,把每个元素赋值给临时变量product,然后Thymeleaf会为每个元素生成一个<li>或<tr>标签。
2. 解决仅显示首个对象的问题
你提到Controller能循环输出所有属性,但Thymeleaf只显示第一个对象,大概率是没有正确使用th:each,而是直接访问了集合的第一个元素(或者Thymeleaf默认取第一个元素)。
常见错误写法
比如你可能写了类似这样的代码(没有th:each):
<!-- 错误:只会显示集合的第一个元素 --> <div> <h4 th:text="${products.name}"></h4> <p th:text="${products.description}"></p> </div>
这种情况下,Thymeleaf会尝试把集合当作单个对象处理,默认取第一个元素的属性,所以只会显示第一条数据。
正确写法修正
只需要把th:each添加到需要重复的元素上,比如每个商品卡片的外层div:
<!-- 正确:遍历整个集合,渲染每个元素 --> <div th:each="product : ${products}" class="product-card"> <h4 th:text="${product.name}"></h4> <p th:text="${product.description}"></p> </div>
这样Thymeleaf会为集合中的每个Product对象生成一个独立的.product-card div,展示所有元素的信息。
如果你的模板结构更复杂,只要记住:把th:each放在需要重复渲染的那个最外层元素上,就能遍历整个集合了。
内容的提问来源于stack exchange,提问作者Jill

