SpringBoot之SpringBoot整合Thymeleaf模板引擎
阿新 • • 發佈:2021-01-21
SpringBoot之SpringBoot整合Thymeleaf模板引擎
新增Thymeleaf場景啟動器
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
編寫控制器程式碼
如果之前有引入過別的模板引擎,可以先註釋掉,防止出現衝突什麼的一些不明錯誤
新增一個Thymeleaf的控制器
ThymeleafIndexController.java
package com.springboot.demo.controller; import com.springboot.demo.model.Flower; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import java.util.Map; /** * @author ZYGisComputer*/ @Controller public class ThymeleafIndexController { @Autowired private Flower flower; @RequestMapping("/thymeleaf") public String thymeleafIndex(Map<String,Object> result){ result.put("flower",flower); return "thymeleaf"; } }
注意:不明白Flower的可以看一下《SpringBoot之讀取配置檔案中自定義的值
編寫模板
為了防止向上次整合FreeMarker翻車,這次配置一下Thymeleaf的一些資訊
在application.yml中配置Thymeleaf的配置
spring: thymeleaf: #prefix:指定模板所在的目錄 prefix: classpath:/templates/ #check-tempate-location: 檢查模板路徑是否存在 check-template-location: true #cache: 是否快取,開發模式下設定為false,避免改了模板還要重啟伺服器,線上設定為true,可以提高效能。 cache: false #suffix 配置模板字尾名 suffix: .html encoding: UTF-8 mode: HTML5
這次直接指定為.html不再翻車
在templates資料夾下建立thymeleaf.html檔案
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> 姓名:<span th:text="${flower.getName()}"></span> 年齡:<span th:text="${flower.getAge()}"></span> </body> </html>
注意:其中在html標籤上增加了名稱空間xmlns:th="http://www.thymeleaf.org"然後在下面就能寫Thymeleaf的語法了
啟動專案訪問一下:
希望不翻車..
一舉成功..舒服
作者:彼岸舞
時間:2021\01\21
內容關於:SpringBoot
本文來源於網路,只做技術分享,一概不負任何責任