Spring Boot如何整合Thymeleaf模板引擎

1949idc 2年前 (2024-09-18) 阅读数 300 #编程语言

要在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页面了。

版权声明

本文内容由互联网用户自发贡献,该文观点仅代表作者本人
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

© 2010 首途云安 & 厦门硕顿信息技术有限公司 & 闽ICP备11016866号  增值电信业务经营许可证:B1-20203020 地址:福建厦门思明区嘉禾路297号1806
高新技术企业
软件产品证书
计算机软件著作权
ISO认证
国家3A企业