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

得到后端傳入的數據的語法為 ${要操作的后端傳入的數據}
- 使用
th:each="user:${users}"遍歷得到每個 user。 - 取出每個 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-->到此這篇關于SpringBoot使用thymeleaf實現一個前端表格方法詳解的文章就介紹到這了,更多相關SpringBoot thymeleaf內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot整合MyBatis實現樂觀鎖和悲觀鎖的示例
這篇文章主要介紹了SpringBoot整合MyBatis實現樂觀鎖和悲觀鎖的示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-09-09
JDBC中Statement和Preparement的使用講解
今天小編就為大家分享一篇關于JDBC中Statement和Preparement的使用講解,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-01-01

