Spring Boot如何整合Thymeleaf模板引擎

小樊
81
2024-09-12 17:59:07

要在Spring Boot中整合Thymeleaf模板引擎,請(qǐng)按照以下步驟操作:

  1. 添加依賴

pom.xml文件中添加Thymeleaf的依賴。將以下代碼添加到<dependencies>標(biāo)簽內(nèi):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  1. 配置Thymeleaf

application.propertiesapplication.yml文件中添加Thymeleaf的配置。以下是一些常用的配置選項(xiàng):

# application.properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML

或者使用YAML格式:

# application.yml
spring:
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    cache: false
    encoding: UTF-8
    mode: HTML
  1. 創(chuàng)建模板文件

src/main/resources/templates目錄下創(chuàng)建Thymeleaf模板文件。例如,創(chuàng)建一個(gè)名為index.html的文件:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title th:text="${title}">Title</title>
</head>
<body>
    <h1 th:text="${message}">Hello, World!</h1>
</body>
</html>
  1. 編寫Controller

創(chuàng)建一個(gè)Spring MVC控制器,用于處理請(qǐng)求并返回Thymeleaf模板。例如:

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MyController {

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("title", "Thymeleaf Integration");
        model.addAttribute("message", "Welcome to Thymeleaf integration with Spring Boot!");
        return "index";
    }
}
  1. 運(yùn)行應(yīng)用程序

啟動(dòng)Spring Boot應(yīng)用程序,然后在瀏覽器中訪問(wèn)http://localhost:8080/。你應(yīng)該能看到Thymeleaf模板引擎渲染的頁(yè)面。

這就是在Spring Boot中整合Thymeleaf模板引擎的方法?,F(xiàn)在你可以開(kāi)始使用Thymeleaf來(lái)構(gòu)建動(dòng)態(tài)HTML頁(yè)面了。

0