千家信息网

Thymeleaf数据迭代的方法是什么

发表于:2025-02-11 作者:千家信息网编辑
千家信息网最后更新 2025年02月11日,本篇内容介绍了"Thymeleaf数据迭代的方法是什么"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
千家信息网最后更新 2025年02月11日Thymeleaf数据迭代的方法是什么

本篇内容介绍了"Thymeleaf数据迭代的方法是什么"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

Thymeleaf数据迭代使用th:each属性,可以迭代数组、List、Set和Map等,数组、List、Set的迭代方法类似,迭代Map则会得到一个java.util.Map.Entry对象。
在迭代过程中,还可以获取迭代状态的变量,如迭代索引、数据集合大小等等。

开发环境:IntelliJ IDEA 2019.2.2
Spring Boot版本:2.1.8

新建一个名称为demo的Spring Boot项目。

1、pom.xml
加入Thymeleaf依赖

            org.springframework.boot            spring-boot-starter-thymeleaf        

2、src/main/java/com/example/demo/user.java

package com.example.demo;public class User {    Integer id;    String name;    public User(Integer id, String name) {        this.id = id;        this.name = name;    }    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }}

3、src/main/java/com/example/demo/TestController.java

package com.example.demo;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;@Controllerpublic class TestController {    @RequestMapping("/")    public String test(Model model){        List users = new ArrayList();        users.add(new User(1,"张三"));        users.add(new User(2,"李四"));        users.add(new User(3,"王五"));        model.addAttribute("users", users);        Map userMap = new HashMap();        userMap.put("a", new User(4, "赵六"));        userMap.put("b", new User(5, "钱七"));        model.addAttribute("userMap", userMap);        return "test";    }}

4、src/main/resources/templates/test.html

        Title    
迭代List
迭代Map
迭代状态对象
上面的iterState是显式声明的迭代状态对象,也可以按默认规划"节点变量名+Stat"获取

浏览器访问:http://localhost:8080,截图如下:

右键查看网页源代码,生成的HTML源码:

        Title    
迭代List
1 张三
2 李四
3 王五
迭代Map
a--4--赵六
b--5--钱七
迭代状态对象
从0开头的索引:0 从1开头的索引:1 数据集合大小:3 当前节点:0 是否第一次迭代:true 是否最后一次迭代:false 是否偶数迭代:false 是否奇数迭代:true
从0开头的索引:1 从1开头的索引:2 数据集合大小:3 当前节点:1 是否第一次迭代:false 是否最后一次迭代:false 是否偶数迭代:true 是否奇数迭代:false
从0开头的索引:2 从1开头的索引:3 数据集合大小:3 当前节点:2 是否第一次迭代:false 是否最后一次迭代:true 是否偶数迭代:false 是否奇数迭代:true
上面的iterState是显式声明的迭代状态对象,也可以按默认规划"节点变量名+Stat"获取
0
1
2
1 张三
2 李四
3 王五

"Thymeleaf数据迭代的方法是什么"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!

0