SpringBoot使用thymeleaf实现前端表格

1. User实体类

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

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

1
2
3
4
5
6
7
8
9
10
11
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";

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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 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 文件夹下

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
        <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">
<td>Trident</td>
                <td>Internet</td>
                <td>[[${user.password}]]</td>
            </tr>
</tbody>
</table>
</div>
            </div>
        </section>
</div>
        </div>
        </div>

到此这篇关于SpringBoot使用thymeleaf实现前端表格的文章就介绍到这了,更多相关SpringBoot thymeleaf内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/code/java/7277.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部