SpringBoot之整合thymeleaf渲染Web頁面

zhangsan分享之家發表於2020-12-26

3.5使用thymeleaf渲染Web頁面

 3.5.1什麼是thymeleaf

thymeleaf是一款用於渲染XML/XHTML/HTML5內容的模板引擎,類似JSP,Velocity,FreeMaker等,它也可以輕易的與Spring MVC等Web框架進行整合作為Web應用的模板引擎。

 3.5.2 Maven依賴

<!--Spring SpringMVC  -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--引入thymeleaf的依賴-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

 3.5.3 配置檔案新增

###ThymeLeaf配置
spring:
  thymeleaf:
    #prefix:指定模板所在的目錄
    prefix: classpath:/templates/
    #check-tempate-location: 檢查模板路徑是否存在
    check-template-location: true
    #cache: 是否快取,開發模式下設定為false,避免改了模板還要重啟伺服器,線上設定為true,可以提高效能。
    cache: true
    suffix:  .html
    encoding: UTF-8
    mode: HTML5

 3.5.4 案例程式碼


import com.mayikt.entity.UserEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

/**
 * @ClassName IndexController
 * @Author 螞蟻課堂餘勝軍 QQ644064779 www.mayikt.com
 * @Version V1.0
 **/
@Controller
public class IndexController {
    @RequestMapping("/myThymeleaf")
    public String myThymeleaf(Map<String, Object> result) {
        result.put("user", new UserEntity("mayikt", 22));
        return "myThymeleaf";
    }
}

 

/**
 * @ClassName UserEntity
 * @Author 螞蟻課堂餘勝軍 QQ644064779 www.mayikt.com
 * @Version V1.0
 **/
public class UserEntity {
    private String userName;
    private Integer age;

    public UserEntity(String userName, Integer age) {
        this.userName = userName;
        this.age = age;
    }

    public String getUserName() {
        return userName;
    }

    public Integer getAge() {
        return age;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

 

 

 

<!DOCTYPE html>
<!--需要在HTML檔案中加入以下語句: -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Show User</title>
</head>
<body>
<table>
    姓名:<span th:text="${user.userName}"></span>
    年齡:<span th:text="${user.age}"></span>
</table>
</body>
</html>

 

 3.5.4 高階寫法

迴圈語句:

<ul th:each="user:${userList}">
    <li th:text="${user.userName}"></li>
    <li th:text="${user.age}"></li>
    <br>
</ul>

 

If判斷:

<span th:if="${user.age>17}">已經成年啦</span>
<span th:if="${user.age<17}">未成年</span>

詳細可以更多語法可以檢視https://www.thymeleaf.org/documentation.html

 

 

1.B站線上學習地址:https://www.bilibili.com/video/BV1Q64y1f7fX 

2. 百度雲盤視訊和文件下載:

連結:https://pan.baidu.com/s/15wAcEczic7I5MvhUizIJkg

提取碼:1234

3.springboot 修訂版本文件和程式碼下載

連結:http://note.youdao.com/noteshare?id=74244e05cc0bc189dbb8873ccfce55cb

相關文章