温馨提示×

Spring Boot如何整合Thymeleaf模板引擎

小樊
81
2024-09-12 17:59:07
栏目: 编程语言

要在Spring Boot中整合Thymeleaf模板引擎,请按照以下步骤操作:

  1. 添加依赖

pom.xml文件中添加Thymeleaf的依赖。将以下代码添加到<dependencies>标签内:

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

application.propertiesapplication.yml文件中添加Thymeleaf的配置。以下是一些常用的配置选项:

# 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. 创建模板文件

src/main/resources/templates目录下创建Thymeleaf模板文件。例如,创建一个名为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

创建一个Spring MVC控制器,用于处理请求并返回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. 运行应用程序

启动Spring Boot应用程序,然后在浏览器中访问http://localhost:8080/。你应该能看到Thymeleaf模板引擎渲染的页面。

这就是在Spring Boot中整合Thymeleaf模板引擎的方法。现在你可以开始使用Thymeleaf来构建动态HTML页面了。

0