2021/03/05

[spring] Spring MVC + Thymeleaf 範例

MVC 是一種設計方式,分別是 ModelViewController 的簡寫。
  • Model:模型,代表儲存資料的 POJO,也可以帶有邏輯,作用為暫時儲存資料之處,並在資料有變化時,更新控制器。
  • View:視圖,解析及處理,並依照模板來產生視圖。
  • Controller:控制器,主要用來處理 view 的反應,決定如何調用 model 及業務層,以及如何將結果返回給 view 並作呈現。
瀏覽器發出 HTTP request 後,web server 收到後會交給 DispatcherServlet,並依照對應的 url mapping 轉交給 controller,controller 會調用 service 然後利用 model 將回覆結果交給 DispatcherServlet。Controller 將 ModelAndView 回傳給 DispatcherServlet 後,交由 ViewResolver 來產生 view。
開發環境為
  • spring-boot:2.6.5.RELEASE
  • tomcat-embed:9.0.60
Controller 使用 @Controller 來標示,@RequestMapping 用來設定 url mapping,此外還有許多其他的 annotation,像 @GetMapping 其實就是 @RequestMapping(method = RequestMethod.GET) 的縮寫,如果 response 沒有要使用 view 來作回應,可以使用 @ResponseBody 直接作回覆。Spring boot 中針對模板引擎的整合,選擇 thymeleaf 而非 jsp,thymeleaf 程式碼更接近 html,可以用瀏覽器直接開啟。
@Controller
@RequestMapping("/controller")
public class HelloController {
    @GetMapping("/hello")
    public String hello(Model model, 
            @RequestParam(defaultValue = "Anonymous") String name) {
        model.addAttribute("name", name);
        return "/th/hello";
    }
}
Thymeleaf 的撰寫方式與 jsp 沒有太大的差異,name 就是 controller 針對 model 新增的屬性。檔案為 html 檔,路徑為 src/main/resources/templates/th/hello.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Hello</title>
    </head>
    <body>
        <p>
            Hello, <span th:text="${name}"> </span>
        </p>
    </body>
</html>
application.properties 中能設定 thymeleaf 屬性,其中將 spring.thymeleaf.cache 設為 false,方便在開發環境下作修改後,馬上就能檢視其變動。
# application.properties
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false
利用 spring-boot-maven-plugin 啟動 spring-boot:run,應用程式開啟後,用瀏覽器打開 http://127.0.0.1:8080/controller/hello?name=cookieandcoke,網頁就會顯示 Hello, cookieandcoke。如果沒有帶 url 中沒有 name,像是 http://127.0.0.1:8080/controller/hello,網頁就會顯示 Hello, Anonymous,其中 Anonymous 就是在 HelloControllerhello 方法 defaultValue 設定的。

程式碼:https://github.com/cookieandcoke/spring-boot-guide/tree/controller-thymeleaf

Reference
https://www.thymeleaf.org/

沒有留言:

張貼留言