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)文章
關(guān)于SpringBoot使用@ExceptionHandler注解局部異常處理
這篇文章主要介紹了關(guān)于SpringBoot使用@ExceptionHandler注解局部異常處理,SpringBoot提供了多種方式來處理異常,在本文中,我們將介紹SpringBoot中的@ExceptionHandler注解,演示如何使用它進行局部異常處理2023-07-07通過代理類實現(xiàn)java連接數(shù)據(jù)庫(使用dao層操作數(shù)據(jù))實例分享
java通過代理類實現(xiàn)數(shù)據(jù)庫DAO操作代碼分享,大家參考使用吧2013-12-12SpringBoot?實現(xiàn)微信推送模板的示例代碼
這篇文章主要介紹了SpringBoot?實現(xiàn)微信推送模板,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-12-12