Thymeleaf模闆使用
1. 簡介
官網:https://www.thymeleaf.org/index.html
Thymeleaf是一種基于服務端的Java模闆引擎技術,具有豐富的标簽語言、函數和表達式。
2. 環境準備
2.1 建立maven項目
2.2 引入依賴
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>thymeleaf</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.4</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.4.4</version>
</plugin>
</plugins>
</build>
</project>
2.3 預設配置
啟動器已經把thymeleaf視圖器配置完成,模闆檔案位置也已經配置完成
- 預設字首:classpath:/templates/
- 預設字尾:.html
在測試中,常常需要關閉頁面緩存
spring:
thymeleaf:
cache: false
3. 快速開始
3.1 啟動類
package top.infinxkj.thymeleaf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class,args);
}
}
3.2 controller
package top.infinxkj.thymeleaf.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class DemoController {
@GetMapping
public String hello(){
return "hello";
}
}
3.3 HTML
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>測試</title>
</head>
<body>
<h1>這是一個測試頁面</h1>
</body>
</html>
注意,把html 的名稱空間,改成:
xmlns:th="http://www.thymeleaf.org"
會有文法提示
3.4 測試
啟動DemoApplication類,打開浏覽器輸入:http://localhost:8080/
