SpringBoot使用thymeleaf實現(xiàn)一個前端表格方法詳解
1. User 實體類
注:這里使用了 Lombok 技術(shù),通過 @Data 注釋自動創(chuàng)建 get,set 方法;通過 @NoArgsConstructor 注釋自動創(chuàng)建無參數(shù)的構(gòu)造方法;通過 @AllArgsConstructor 注釋自動創(chuàng)建有參數(shù)構(gòu)造方法
如果不想使用,可以自行創(chuàng)建get,set 方法以及構(gòu)造方法
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 類
創(chuàng)建一 user 的 list ,使用 addAttribute() 方法將其放入 medol 中,以便前端取出 medol 中的數(shù)據(jù)
注意:thymeleaf解析不能帶 html 后綴,因此轉(zhuǎn)發(fā)到 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){
// 表格內(nèi)容的遍歷
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 文件
創(chuàng)建 dynamic_table.html 文件在 templates 的 table 文件夾下

得到后端傳入的數(shù)據(jù)的語法為 ${要操作的后端傳入的數(shù)據(jù)}
- 使用
th:each="user:${users}"遍歷得到每個 user。 - 取出每個 user 值放入表格中時 可以使用
th:text="${user.userName}"也可以使用[[${user.password}]]
注: stats 為自增 id,用于記錄遍歷到第幾個 user,得到數(shù)量的方法為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-->到此這篇關(guān)于SpringBoot使用thymeleaf實現(xiàn)一個前端表格方法詳解的文章就介紹到這了,更多相關(guān)SpringBoot thymeleaf內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java使用POI導(dǎo)出Excel(二):多個sheet
這篇文章介紹了Java使用POI導(dǎo)出Excel的方法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-10-10
Java組件FileUpload上傳文件實現(xiàn)代碼
這篇文章主要為大家詳細介紹了Java組件FileUpload上傳文件實現(xiàn)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-06-06
java使用FuncGPT慧函數(shù)對Mybatis進行一對一查詢映射處理
這篇文章主要介紹了java使用FuncGPT慧函數(shù)對Mybatis進行一對一查詢映射處理,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09
Springboot微服務(wù)項目整合Kafka實現(xiàn)文章上下架功能
這篇文章主要介紹了Springboot微服務(wù)項目整合Kafka實現(xiàn)文章上下架功能,包括Kafka消息發(fā)送快速入門及相關(guān)功能引入,本文通過示例代碼給大家介紹的非常詳細,需要的朋友可以參考下2022-07-07

