SpringBoot——Thymeleaf中使用th:each遍历数组、List、Map_thymeleaf th:each-程序员宅基地

技术标签: # 【SpringBoot】  

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这个模板引擎中的内容,所以没有过多的考虑这个问题,希望大家谅解!!!

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_43823808/article/details/117171690

智能推荐

Code Blocks 安装后编译出现“编译器无效”问题。_codeblocks编译器无效-程序员宅基地

文章浏览阅读2.2k次。编写程序并编译后出现如上图报错,大致意思为:编译器安装无效,所以编译器无法运行编译器,请检查编译器路径有没有正确配置,并且给出了个修改步骤,最后说设置的路径没有找到编译器文件。。。解决方法:S1:首先我们要确定我们下载安装Code Blocks是带有编译器版本的,就是带有MinGW的版本:下载地址:http://www.codeblocks.org/downloads/26S2:然后给软件指定MinGW的所在路径:菜单栏Settings -> Compil..._codeblocks编译器无效

神操作!一行Python代码搞定一款游戏?给力!-程序员宅基地

文章浏览阅读475次。点击上方“Python大本营”,选择“置顶公众号”Python大本营 IT人的职业提升平台来源:pypl编程榜一直以来Python长期霸占编程语言排行榜前三位,其简洁,功能强大的特性..._python好游戏代码

ubuntu 1604 random: crng init done 后无反应_random: fast init done-程序员宅基地

文章浏览阅读2.4k次。服务器安装Ubuntu1604报错报错内容:kernel panic - not syncing attempted to kill the idle taskrandom: fast init donerandom: crng init done错误原因:使用了错误的安装镜像,CPU位宽64位使用了i386的安装镜像,切换amd64安装镜像后无报错..._random: fast init done

Git学习系列(一)初识Git-程序员宅基地

文章浏览阅读718次。Git作为一个版本控制工具,在工作中我们常常会用到它,尤其是在移动开发中,Git可谓是版本管理神器。下面让我们来认识一下Git:Git是一个分布式版本控制软件,它是由Linux的作者Linus用C写的一个分布式版本控制系统。如果大家对Git的历史比较感兴趣,可以点击链接进入官网了解:A Short History of GitGit主要特点有如下:1、速度:Git在本地上保存着所有

餐饮行业怎么才能玩转大数据?-程序员宅基地

文章浏览阅读154次。编者按:用数据将传统餐饮门店信息搬到线上,大众点评兴起;以数据化为基础,餐饮门店经营实现移动化,点单、叫号、排队模式火了。目前,餐饮行业的数据应用更多在供应链管理和餐饮门店运营状况实时监控分析,每个餐饮商家各自为战,实际数据的应用比大数据的应用更多,而大数据更多用于用户画像和少数大企业的经营管理。不过,基于大数据在电商的应用和餐饮的发展趋势,大数据的应..._如何获得每个城市的餐饮大数据

Dialog异常 Unable to add window, token not valid_token not valid-程序员宅基地

文章浏览阅读584次。好记性不如烂笔头问题描述 Activity 延时显示 Dialog ,在显示之前, Activity 已经销毁 报错 Unable to add window -- token android.os.BinderProxy@e6ee7d8 is not valid; is your activity running?问题分析 错误信息很明确,是没有 token 导致的. 而 toke_token not valid

随便推点

配置NGINX同时运行 https 和 http_nginx 和 http无法同时启动-程序员宅基地

文章浏览阅读406次。SSL 是需要申请证书的,key和PEM文件要放到服务器路径。然后NGINX下要进行443端口和80端口的绑定。server { listen 80; server_name ietaiji.com www.ietaiji.com; root "D:/aaa/WWW/ietaiji"; index index.html_nginx 和 http无法同时启动

总结:linux之Service_linux service-程序员宅基地

文章浏览阅读1.3w次,点赞9次,收藏60次。service与systemctl关系梳理开机启动梳理_linux service

揭开数据中心光模块利润之源-程序员宅基地

文章浏览阅读194次。在数据中心里,光模块毫不起眼,当我们在高谈阔论各种数据中心高大上技术时,很少提及到光模块。不过,光模块却是数据中心的必需品,哪个数据中心也离不开光模块,而且需要的数量还不少,一块48端口网络设备就需要48个光模块,而一台框式网络设备通常有数百个端口,这些端口如果都使用上就需要数百个光模块,这样算起来数据中心需要的光模块数量是惊人的。数据中心在进行网络投资..._光模块 占 数据中心 成本

Java NIO SocketChannel简述及示例_niosocketchannel-程序员宅基地

文章浏览阅读596次,点赞2次,收藏3次。SocketChannel简述及demoJAVA NIO之SocketChannel1. 简述2. 特点3. 解决问题4. demo功能5. 工作原理6. 代码示例7. 涉及知识扩充JAVA NIO之SocketChannel1. 简述NIO(Non-blocking I/O,在Java领域,也称为New I/O),是一种同步非阻塞的I/O模型,也是I/O多路复用的基础,已经被越来..._niosocketchannel

docker内的debian9使用ntpdate同步时间时报错step-systime: Operation not permitted-程序员宅基地

文章浏览阅读3.8k次。场景在docker下使用tzselect设置时间,最后提示编辑profile追加TZ='Asia/Shanghai'; export TZvim/etc/profilesource /etc/profile发现时区正确了,但时间和宿主机相差几分钟....使用 ntpdate cn.pool.ntp.org同步时间提示ntpdate[534]: step-systime: Operation not permitted使用 ntpdate ntp.s..._step-systime: operation not permitted

基于功能安全的车载计算平台开发:硬件层面_mcu 不同通道 共因-程序员宅基地

文章浏览阅读537次,点赞18次,收藏6次。如果不具备关于复杂元器件的安全故障比例的详细信息,可假定安全故障的保守比例为50%,并假定通过内部自检和外部看门狗(表中的安全机制SM4)达到对违背安全目标的总体覆盖率为90%。这里的意图不是一定需要全面的分析,比如要求对于微控制器内或者来自于一个复杂的PCB板上任何理论可能的信号组合的桥接故障进行详尽的分析。根据硬件故障对安全目标产生影响的不同,硬件故障可分为安全相关故障与非安全相关故障,其中安全相关故障又进一步分为单点故障、残余故障、多点可探测故障、多点可感知故障、多点潜伏故障与安全故障。