--- title: 'Spring Boot Controller (1) Thymeleaf簡單例子' disqus: hackmd --- ###### tags: `SpringBoot` Spring Boot Controller (1) Thymeleaf簡單例子 === [TOC] ## 適用場景 了解spring boot 的controller的基本知識 ## 先備條件 引入thymeleaf套件 ## 檔案結構目錄 ![](https://i.imgur.com/60LatKk.png) ## 程式碼部分 ### DemoController ```java= package com.allproducts.ai_center.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class DemoController { @GetMapping("/test404") public String test404() { return "index"; } @GetMapping("/test500") public String test500() { int i = 1 / 0; return "index"; } @GetMapping("/welcome") public String welcome() { int i = 1 / 0; return "welcome"; } @GetMapping("/truewelcome") public String truewelcome() { return "welcome"; } @GetMapping("/") @ResponseBody public String index() { return "Greetings from Spring Boot!"; } @GetMapping("/getBlogger") public String getBlogger(Model model) { Blogger blogger = new Blogger(1L, "理性思考", "123456"); model.addAttribute("blogger", blogger); return "blogger"; } @GetMapping("/getList") public String getList(Model model) { Blogger blogger1 = new Blogger(1L, "理性思考", "123456"); Blogger blogger2 = new Blogger(2L, "感同身受", "123456"); List<Blogger> list = new ArrayList<>(); list.add(blogger1); list.add(blogger2); model.addAttribute("list", list); return "list"; } } ``` ### list.html ```htmlembedded= <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <html lang="en"> <head> <meta charset="UTF-8"> <title>博主資訊</title> </head> <body> <form action="" th:each="blogger : ${list}" > 使用者編號:<input name="id" th:value="${blogger.id}"/><br> 使用者姓名:<input type="text" name="password" th:value="${blogger.name}"/><br> 登入密碼:<input type="text" name="username" th:value="${blogger.getPassword()}"/> </form> </body> </html> ``` ![](https://i.imgur.com/w2oYnZ4.png) ## 解析 可以注意到 index() 還有 truewelcome() 這兩個函數的返回型態雖然都是String, 但是由於index()函數新增了@ResponseBody 所以說 1. index() 函數返回的是單純的字串"Greetings from Spring Boot!" 2. truewelcome() 函數返回的則是 welcome.html 頁面! 另外也要注意 /test404 /welcome 這些路由是不可以重複的,但是我們卻可以出現重複的返回頁面 像是 welcome() 函數還有 truewelcome函數雖然路由不一樣,但是他們的返回頁面可以是一樣的。 但是但是因為welcome函數有一個bug, int i=1/0 會有error產生所以此時不會返回welcome.html頁面,反而會返回 ![](https://i.imgur.com/USRZPiW.png) 可以看出,其實和處理單個物件資訊差不多,Thymeleaf 使用 th:each 進行遍歷,${} 取 model 中傳過來的引數,然後自定義 list 中取出來的每個物件,這裡定義為 blogger。表單裡面可以直接使用 ${物件.屬性名} 來獲取 list 中物件的屬性值,也可以 使用 ${物件.get 方法} 來獲取,這點和上面處理物件資訊是一樣的,但是不能使用 *{屬性名} 來獲取物件中的屬性,thymeleaf 模板獲取不到。 ## 參考連結 [spring boot 整合模板引擎](https://www.gushiciku.cn/pl/gHp9/zh-tw)