SpringBoot自帶模板引擎Thymeleaf使用詳解
SpringBoot是一個(gè)流行的Java框架,它提供了許多功能和插件,以簡(jiǎn)化Web應(yīng)用程序的開發(fā)過程。其中之一是Thymeleaf模板引擎,它是一個(gè)流行的Java模板引擎,用于在Web應(yīng)用程序中渲染HTML頁(yè)面。
在SpringBoot中使用Thymeleaf非常簡(jiǎn)單,以下是使用Thymeleaf作為模板引擎的步驟:
添加依賴
首先,在項(xiàng)目的pom.xml文件中添加Thymeleaf的依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>{version}</version>
</dependency>
其中{version}是SpringBoot的版本號(hào)。
配置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
這些配置項(xiàng)指定了模板文件的存放路徑、文件名后綴、模板模式、編碼格式和內(nèi)容類型。
創(chuàng)建模板文件
創(chuàng)建一個(gè)HTML模板文件,例如index.html,并將其放置在
/src/main/resources/templates/目錄下。在該文件中,你可以使用Thymeleaf的語(yǔ)法來(lái)定義動(dòng)態(tài)內(nèi)容。
例如,以下是一個(gè)簡(jiǎn)單的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>
在這個(gè)例子中,我們使用了th:text屬性來(lái)定義一個(gè)動(dòng)態(tài)文本,它會(huì)被渲染為頁(yè)面上的標(biāo)題。
創(chuàng)建控制器
創(chuàng)建一個(gè)控制器類,例如IndexController.java,并將其放置在/src/main/java/目錄下。在該類中,你可以使用@Controller和@GetMapping注解來(lái)定義一個(gè)處理HTTP GET請(qǐng)求的方法。
例如,以下是一個(gè)簡(jiǎn)單的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";
}
}
在這個(gè)例子中,我們使用@GetMapping注解來(lái)定義一個(gè)處理/路徑的HTTP GET請(qǐng)求的方法。該方法將"title"屬性添加到Model對(duì)象中,并將其返回值設(shè)置為"index",這表示渲染index.html模板文件。
- 啟動(dòng)應(yīng)用程序并查看結(jié)果
啟動(dòng)SpringBoot應(yīng)用程序并訪問首頁(yè)(即/路徑),你應(yīng)該會(huì)看到一個(gè)帶有"Welcome to my site"標(biāo)題的頁(yè)面。這是因?yàn)榭刂破鞣椒▽?title"屬性添加到Model對(duì)象中,并返回了"index"字符串,這導(dǎo)致Thymeleaf引擎渲染了index.html模板文件,并將"title"屬性的值插入到h1元素中。
以上就是在SpringBoot中使用Thymeleaf模板引擎的簡(jiǎn)單示例。Thymeleaf具有許多其他功能和特性,例如循環(huán)、條件語(yǔ)句、變量替換等等,可以讓你更加靈活地渲染HTML頁(yè)面。如果你想了解更多關(guān)于Thymeleaf的信息,請(qǐng)查看官方文檔或參考相關(guān)教程和示例代碼。