java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot thymeleaf

SpringBoot使用thymeleaf实现前端表格

作者:刘婉晴

虽然现在流行前后端分离,但是后端模版在一些关键地方还是非常有用的,例如邮件模版、代码模版等。当然也不排除一些古老的项目后端依然使用动态模版。Thymeleaf 简洁漂亮、容易理解,并且完美支持 HTML5,可以直接打开静态页面,同时不新增标签,只需增强属性

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 文件夹下

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

注: 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-->

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

您可能感兴趣的文章:
阅读全文