SpringBoot——Thymeleaf中使用th:each遍历数组、List、Map

简介: SpringBoot——Thymeleaf中使用th:each遍历数组、List、Map

1.写在前面


这个属性非常常用,比如从后台传来一个对象集合那么就可以使用此属性遍历输出,它与JSTL 中的<c: forEach>类似,此属性既可以循环遍历集合,也可以循环遍历数组及 Map

2.应用举例


2.1 遍历数组

首先,我们准备一个model类。

这里使用了lombok下的一个注解 @Data,它可以帮助我们自动生成 get/set 方法、toString()等。但是我们在这个类中是看不到的,查看的方法是:点击这个类,然后按 Alt + 7,即可查看。

package com.songzihao.springboot.model;
import lombok.Data;
/**
 *
 */
@Data
public class User {
    private Integer id;
    private String name;
    private String phone;
    private String address;
}


之后,我们写一个控制层,其中有一个请求方法。

package com.songzihao.springboot.controller;
import com.songzihao.springboot.model.User;
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;
/**
 *
 */
@Controller
public class UserController {
    @RequestMapping(value = "/each/array")
    public String eachArray(Model model) {
        User[] userArray = new User[10];
        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setId(i);
            user.setName("宋小" + i);
            user.setPhone("1853790565" + i);
            user.setAddress("洛阳市涧西区XX路" + i + "号");
            userArray[i] = user;
        }
        model.addAttribute("userArray",userArray);
        return "eachArray";
    }
}

然后是这个请求方法对应的html页面。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>循环遍历Array数组</title>
</head>
<body>
    <div th:each="user,userStat:${userArray}">
        <span th:text="${userStat.index}"></span>
        <span th:text="${user.id}"></span>
        <span th:text="${user.name}"></span>
        <span th:text="${user.phone}"></span>
        <span th:text="${user.address}"></span>
    </div>
</body>
</html>

最后在核心配置文件中添加以下内容,启动入口类,测试。

#关闭Thymeleaf页面的缓存开关
spring.thymeleaf.cache=false
#thymeleaf 模版前缀,默认值,可选项
spring.thymeleaf.prefix=classpath:/templates/
#thymeleaf 模版后缀,默认值,可选项
spring.thymeleaf.suffix=.html


package com.songzihao.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

2.2 遍历List


model里面的User类、核心配置文件、项目启动入口类和上面的例子是一样的,这里就不再给出代码了。

下面直接给出控制层中对应的方法和对应的html页面。

package com.songzihao.springboot.controller;
import com.songzihao.springboot.model.User;
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;
/**
 *
 */
@Controller
public class UserController {
    @RequestMapping(value = "/each/list")
    public String userList(Model model) {
        List<User> userList=new ArrayList<>();
        for (int i=0;i<10;i++) {
            User user=new User();
            user.setId(1000 + i);
            user.setName("宋小" + i);
            user.setPhone("1364388173" + i);
            user.setAddress("郑州市金水区XX路" + i + "号");
            userList.add(user);
        }
        model.addAttribute("userList",userList);
        return "eachList";
    }
}

th:each="user, userStat : ${userList}" 中的 ${userList} 是后台传过来的集合

user:定义变量,去接收遍历${userList}集合中的一个数据
userStat${userList} 循环体的信息
其中 user userStat 自己可以随便取名
userStat 是循环体的信息,通过该变量可以获取如下信息

index:当前迭代对象的 index (从 0 开始计算)

count:当前迭代对象的个数(从 1 开始计算)这两个用的较多
size:
被迭代对象的大小
current:
当前迭代变量
even/odd:
布尔值,当前循环是否是偶数/奇数(从 0 开始计算)
first:
布尔值,当前循环是否是第一个
last:
布尔值,当前循环是否是最后一个
注意:循环体信息 userStat 也可以不定义,则默认采用迭代变量加上 Stat 后缀,即 userStat

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>循环遍历List集合</title>
</head>
<body>
    <!--
        user:定义变量,去接收遍历${userList}集合中的每一个数据
        userStat:当前循环的对象状态的变量(可以不写), ${userList} 循环体的信息
        userList:当前循环的集合
    -->
    <div th:each="user,userStat:${userList}">
        <span th:text="${userStat.index}"></span>
        <span th:text="${user.id}"></span>
        <span th:text="${user.name}"></span>
        <span th:text="${user.phone}"></span>
        <span th:text="${user.address}"></span>
    </div>
</body>
</html>

2.3 遍历Map


model里面的User类、核心配置文件、项目启动入口类和上面的例子是一样的,这里就不再给出代码了。

下面直接给出控制层中对应的方法和对应的html页面。

package com.songzihao.springboot.controller;
import com.songzihao.springboot.model.User;
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;
/**
 *
 */
@Controller
public class UserController {
    @RequestMapping(value = "/each/map")
    public String eachMap(Model model) {
        Map<Integer,Object> userMaps = new HashMap<Integer, Object>();
        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setId(1000 + i);
            user.setName("宋小" + i);
            user.setPhone("1310179264" + i);
            user.setAddress("洛阳市涧西区XX路" + i + "号");
            userMaps.put(i,user);
        }
        model.addAttribute("userMaps",userMaps);
        return "eachMap";
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>循环遍历Map集合</title>
</head>
<body>
    <div th:each="user,userStat:${userMaps}">
        <span th:text="${userStat.count}"></span>
        <span th:text="${user.key}"></span>
        <span th:text="${user.value}"></span>
        <span th:text="${user.value.id}"></span>
        <span th:text="${user.value.name}"></span>
        <span th:text="${user.value.phone}"></span>
        <span th:text="${user.value.address}"></span>
    </div>
</body>
</html>

最后说一下,可能这三个例子中遍历出来的结果,不太好看😂😂😂,但是这里纯粹是为了学习Thymeleaf这个模板引擎中的内容,所以没有过多的考虑这个问题,希望大家谅解!!!

相关文章
|
2月前
|
Dart
Dart之集合详解(List、Set、Map)
Dart之集合详解(List、Set、Map)
44 1
|
6天前
|
存储 安全 Java
java集合框架复习----(4)Map、List、set
这篇文章是Java集合框架的复习总结,重点介绍了Map集合的特点和HashMap的使用,以及Collections工具类的使用示例,同时回顾了List、Set和Map集合的概念和特点,以及Collection工具类的作用。
java集合框架复习----(4)Map、List、set
|
6天前
|
前端开发 Java Spring
springboot+thymeleaf+bootstrap 超级无敌简洁的页面展示 商城管理页面
这篇文章展示了一个使用Spring Boot、Thymeleaf和Bootstrap框架开发的简洁、响应式的商城管理页面,包括美食介绍、产品详情、购物车等功能,适合初学者学习和使用。
springboot+thymeleaf+bootstrap 超级无敌简洁的页面展示 商城管理页面
|
6天前
|
Java 数据库 Spring
springboot+thymeleaf中前台页面展示中、将不同的数字替换成不同的字符串。使用条件运算符
这篇文章介绍了如何在Spring Boot和Thymeleaf框架中使用条件运算符来根据数字字段的值动态替换显示不同的字符串,例如将订单状态的数字0和1替换为"未付款"和"已付款"等。
springboot+thymeleaf中前台页面展示中、将不同的数字替换成不同的字符串。使用条件运算符
|
1月前
|
JavaScript API
js【最佳实践】遍历数组的八种方法(含数组遍历 API 的对比)for,forEach,for of,map,filter,reduce,every,some
js【最佳实践】遍历数组的八种方法(含数组遍历 API 的对比)for,forEach,for of,map,filter,reduce,every,some
39 1
|
1月前
|
文字识别 Java
文本,文字识别07,SpringBoot服务开发-入参和返回值,编写接口的时候,要注意识别的文字返回的是多行,因此必须是List集合,Bean层,及实体类的搭建
文本,文字识别07,SpringBoot服务开发-入参和返回值,编写接口的时候,要注意识别的文字返回的是多行,因此必须是List集合,Bean层,及实体类的搭建
|
2月前
|
存储 安全 Java
Java集合详解:Set, Map, Vector, List的对比与联系
Java集合框架核心包括List、Set、Map和Vector。List允许重复元素,如ArrayList(适合读取)和LinkedList(适合插入删除)。Set不允许重复,有HashSet(无序)和TreeSet(排序)。Map存储键值对,HashMap(无序)和TreeMap(排序)。Vector是线程安全的ArrayList替代品,但在多线程环境下使用。选择集合类型应根据应用场景,如有序、无序、键值对需求及线程安全考虑。
|
2月前
|
存储 安全 Java
Java 集合(List、Set、Map 等)相关问答归纳再整理
HashMap 中使用键对象来计算 hashcode 值 HashSet 使用成员对象来计算 hashcode 值,对于两个对象来说hashcode 可能相同,所以 equals() 方法用来判断对象的相等性,如果两个对象不同的话,那么返回 false。 HashMap 比较快,因为是使用唯一的键来获取对象,HashSet 较 HashMap 来说比较慢。 4.1.3 HashMap 与 TreeMap
20 2
|
2月前
|
Java
Java list中的对象转为list,list中的对象转为map
Java list中的对象转为list,list中的对象转为map
41 1
|
2月前
|
前端开发 Java Spring
Spring Boot中使用Thymeleaf进行页面渲染
Spring Boot中使用Thymeleaf进行页面渲染