SpringBoot自帶模板引擎Thymeleaf使用詳解
SpringBoot是一個流行的Java框架,它提供了許多功能和插件,以簡化Web應用程序的開發過程。其中之一是Thymeleaf模板引擎,它是一個流行的Java模板引擎,用于在Web應用程序中渲染HTML頁面。
在SpringBoot中使用Thymeleaf非常簡單,以下是使用Thymeleaf作為模板引擎的步驟:
添加依賴
首先,在項目的pom.xml文件中添加Thymeleaf的依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>{version}</version>
</dependency>
其中{version}是SpringBoot的版本號。
配置Thymeleaf
在application.properties或application.yml文件中添加以下配置:
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
這些配置項指定了模板文件的存放路徑、文件名后綴、模板模式、編碼格式和內容類型。
創建模板文件
創建一個HTML模板文件,例如index.html,并將其放置在
/src/main/resources/templates/目錄下。在該文件中,你可以使用Thymeleaf的語法來定義動態內容。
例如,以下是一個簡單的index.html文件:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Welcome to my site</title>
</head>
<body>
<h1 th:text="${title}">Hello World!</h1>
</body>
</html>
在這個例子中,我們使用了th:text屬性來定義一個動態文本,它會被渲染為頁面上的標題。
創建控制器
創建一個控制器類,例如IndexController.java,并將其放置在/src/main/java/目錄下。在該類中,你可以使用@Controller和@GetMapping注解來定義一個處理HTTP GET請求的方法。
例如,以下是一個簡單的IndexController類:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("title", "Welcome to my site");
return "index";
}
}
在這個例子中,我們使用@GetMapping注解來定義一個處理/路徑的HTTP GET請求的方法。該方法將"title"屬性添加到Model對象中,并將其返回值設置為"index",這表示渲染index.html模板文件。
- 啟動應用程序并查看結果
啟動SpringBoot應用程序并訪問首頁(即/路徑),你應該會看到一個帶有"Welcome to my site"標題的頁面。這是因為控制器方法將"title"屬性添加到Model對象中,并返回了"index"字符串,這導致Thymeleaf引擎渲染了index.html模板文件,并將"title"屬性的值插入到h1元素中。
以上就是在SpringBoot中使用Thymeleaf模板引擎的簡單示例。Thymeleaf具有許多其他功能和特性,例如循環、條件語句、變量替換等等,可以讓你更加靈活地渲染HTML頁面。如果你想了解更多關于Thymeleaf的信息,請查看官方文檔或參考相關教程和示例代碼。