天天看點

初學者idea web項目搭建之路(四) thymeleaf模闆引擎

 前言

自己摸索了一陣後,在網絡上找了一個入門的spring boot視訊看了一下,有如醍醐灌頂一般,瞬間就築基成功突破了,畢竟學習知識還是成體系的好。

模闆引擎依賴引入

首先吧抛出兩個官網spring官網,thymeleaf官網,其實吧,你要用别人的東西,肯定是通過人家官網提供的demo和doc文檔學習最好,而且現在浏覽器都帶有翻譯,準确率也挺高,對我們這些詞彙量極低的人倒是一個福利。

ok,依賴包如下,沒有配置版本号,因為下哪個版本的spring boot 會幫我們決定,其實我覺得吧,可能配置了第一個就行了,後面兩個會自動依賴進去。

// 添加 Thymeleaf 的依賴
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.thymeleaf:thymeleaf-spring5'
    implementation 'org.thymeleaf.extras:thymeleaf-extras-java8time'
           

因為使用的是spring boot 是以也沒有其它更多的配置了,開箱即用。

簡單demo

依賴導入了,來個簡單demo吧,也隻能是簡單demo了,深入的,我也還沒去了解。

首先,我們在controller包下建個TestController,代碼如下。

重點是 @Controller标簽和@RequestMapping标簽,@Controller指明這是一個控制器,@RequestMapping指明通路位址

package org.ironman.ticketsellingsystem.controller;


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.Map;
//@Controller 和 @RestController 是有差別的。@RestController 相當于@[email protected]
@Controller
public class TestController {
    @RequestMapping("/test")
    public String index(Model model) {
        model.addAttribute("hello", "hello world");
        return "test";
    }
}
           

然後,在Templates檔案夾下,建立test.html,代碼如下。示例代碼官網的doc文檔裡是有的,我也是copy了一下。

重點是xmlns:th="http://www.thymeleaf.org"這句,引入thymeleaf,${hello}與控制器中add的屬性名是一緻的。“test”即是我們要傳回的頁面,注意我注釋中寫的東西,若是寫的@RestController,那隻會列印test字元串。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
    <title>im test page</title>
</head>
<body>
<p th:text="${hello}">Welcome to our grocery store!</p>
</body>
           

結果如下。

初學者idea web項目搭建之路(四) thymeleaf模闆引擎

模闆引擎的話就是  ,資料+模闆=頁面。資料在控制器中設定,在模闆中用${屬性名}辨別出來,到最後生成頁面時,将控制器中的資料替換過去就生成了我們實際的界面。很友善的說。