【SpringBoot 】结合thymeleaf的一个前端表格展示的小小Demo

1. User 实体类

注:这里使用了 Lombok 技术,通过 @Data 注释自动创建 get,set 方法;通过 @NoArgsConstructor 注释自动创建无参数的构造方法;通过 @AllArgsConstructor 注释自动创建有参数构造方法

如果不想使用,可以自行创建get,set 方法以及构造方法

import jdk.nashorn.internal.objects.annotations.Constructor;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
@Data
public class User {
    private String userName;
    private String password;
}

2. Controller 类

创建一 user 的 list ,使用 addAttribute() 方法将其放入 medol 中,以便前端取出 medol 中的数据

注意:thymeleaf解析不能带 html 后缀,因此转发到 table下的dynamic_table.html 文件要写成 return "table/dynamic_table";

package com.wanqing.admin.controller;

import com.wanqing.admin.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Arrays;
import java.util.List;

@Controller
public class TableController {
    
    @GetMapping("/dynamic_table")
    public String dynamic_table(Model model){
        // 表格内容的遍历
        List<User> users = Arrays.asList(new User("刘婉晴", "520131"),
                new User("加油","aaa"),
                new User("不可以放弃","come on"));
        model.addAttribute("users", users);
        return "table/dynamic_table"; // thymeleaf解析不能带 html 后缀
    }
    
}

3. html 文件

创建 dynamic_table.html 文件在 templates 的 table 文件夹下
在这里插入图片描述

得到后端传入的数据的语法为 ${要操作的后端传入的数据}

  1. 使用 th:each="user:${users}" 遍历得到每个 user。
  2. 取出每个 user 值放入表格中时 可以使用 th:text="${user.userName}" 也可以使用[[${user.password}]]

注: stats 为自增 id,用于记录遍历到第几个 user,得到数量的方法为th:text="${stats.count}",用 逗号 与 user 隔开

        <!--body wrapper start-->
        <div class="wrapper">
        <div class="row">
        <div class="col-sm-12">
        <section class="panel">
	       <div class="panel-body">
	        <div class="adv-table">
	        <table  class="display table table-bordered table-striped" id="dynamic-table">
	        <thead> <!--标头-->
	        <tr>
	            <th>#</th>
	            <th>用户名</th>
	            <th>密码</th>
	        </tr>
	        </thead>
	        <tbody> <!--标体-->
	        <tr class="gradeX" th:each="user,stats:${users}">
	            <td th:text="${stats.count}">Trident</td>
	            <td th:text="${user.userName}">Internet</td>
	            <td>[[${user.password}]]</td>
	        </tr>
	        </tbody>
	        </table>
	        </div>
	        </div>
        </section>
        </div>
        </div>
        </div>
        <!--body wrapper end-->
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值