springboot thymeleaf 的配置

springboot 文章 2023-04-17 13:51 1805 0 全屏看文

AI助手支持GPT4.0

要在 Spring Boot 应用程序中使用 Thymeleaf 模板引擎,您需要执行以下步骤:


在 pom.xml 或 build.gradle 中添加 Thymeleaf 和 Spring Boot Starter Thymeleaf 的依赖项。例如,在 Maven 中,您可以将以下依赖项添加到 pom.xml 文件中:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>


在 application.properties 或 application.yml 中配置 Thymeleaf 属性。例如,在 application.properties 文件中,您可以设置以下属性:

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

这些属性控制了 Thymeleaf 模板引擎的缓存、模式、编码、模板文件夹前缀和后缀等行为。


创建一个包含 Thymeleaf 模板的 HTML 文件,并将其放置在 resources/templates 目录下(或根据前面的配置属性所指定的模板文件夹)。例如,创建一个名为 "index.html" 的模板文件,其中包含以下内容:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf Template</title>
</head>
<body>
    <h1 th:text="${title}">Title</h1>
    <p th:text="${content}">Content</p>
</body>
</html>


创建一个 Spring MVC 控制器,将模型数据填充到 Thymeleaf 模板中。例如:

@Controller
public class MyController {

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("title", "Hello, Thymeleaf!");
        model.addAttribute("content", "Welcome to my Thymeleaf template.");
        return "index";
    }
}

在这个例子中,我们通过 model 参数向 Thymeleaf 模板中传递了两个变量:"title" 和 "content"。


运行应用程序,并访问 http://localhost:8080/ 查看 Thymeleaf 模板渲染的效果。


这就是使用 Spring Boot 和 Thymeleaf 的基本配置和使用方法。当然,根据您的实际需求、场景和功能,可能需要更复杂的配置和使用方式。

-EOF-

AI助手支持GPT4.0