spring boot 整合thyemleaf基本使用 迭代(五)
阿新 • • 發佈:2018-11-11
第一小節:主要是在html遍歷出來controller層的List,這裡類似於foreach.
controller層裡面新建List集合的物件。這裡注意實體類。
model.addAttribute("list",list); key-value的鍵值對。
html層
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <table border="1"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> <!--這裡的u是使用者自定義的,這個自己取值--> <tr th:each="u:${list}"> <td th:text="${u.userid}"></td> <td th:text="${u.username}"></td> <td th:text="${u.userage}"></td> </tr> </table> </body> </html>
Controller層
@RequestMapping("show3") public String showInfo3(Model model){ List<Users> list=new ArrayList<>(); list.add(new Users(1,"張三",20)); list.add(new Users(2,"李四",22)); list.add(new Users(3,"王五",24)); model.addAttribute("list",list); return "index3"; }
實體類
結果:
第二小節:
each迭代 狀態變數var
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <table border="1"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> <th>Index</th> <th>Count</th> <th>Size</th> <th>Even</th> <th>Odd</th> <th>First</th> <th>Last</th> </tr> <tr th:each="u,var :${list}"> <td th:text="${u.userid}"></td> <td th:text="${u.username}"></td> <td th:text="${u.userage}"></td> <td th:text="${var.index}"></td> <td th:text="${var.count}"></td> <td th:text="${var.size}"></td> <td th:text="${var.even}"></td> <td th:text="${var.odd}"></td> <td th:text="${var.first}"></td> <td th:text="${var.last}"></td> </tr> </table> </body> </html>
controller層和第一小節一樣。
結果
index當前迭代器的索引 從0開始
count 當前迭代物件的計數 從1開始
size 迭代物件的長度
even/odd 布林值 當前迴圈是否為偶數/奇數 從0開始
first/last 布林值 當前迴圈是否是第一條/對後一條,如果是返回true 否則 false
第三小節:通過th:each迭代Map
首先:html網頁
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <table border="1"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> <tr th:each="maps:${map}"> <td th:text="${maps}"></td> </tr> </table> <table border="1"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> <!--兩次迭代--> <tr th:each="maps:${map}"> <td th:each="entry:${maps}" th:text="${entry.value.userid}"></td> <td th:each="entry:${maps}" th:text="${entry.value.username}"></td> <td th:each="entry:${maps}" th:text="${entry.value.userage}"></td> </tr> </table> </body> </html>
然後 controller層
@RequestMapping("show4") public String showInfo4(Model model){ Map<String,Users> map=new HashMap<>(); map.put("u1",new Users(1,"張三",20)); map.put("u2",new Users(2,"李四",22)); map.put("u3",new Users(3,"王五",24)); model.addAttribute("map",map); return "index4"; }
結果: