专业的JAVA编程教程与资源

网站首页 > java教程 正文

Spring Boot整合Thymeleaf模板引擎的详细教程

temp10 2025-01-23 21:41:37 java教程 14 ℃ 0 评论

Thymeleaf是现阶段比较流行的一种Java模板引擎技术,可以快速且方便的在Spring Boot项目中开发动态的HTML页面在Spring Boot Web开发方面起到了关键的重要作用。下面,我们就来详细解介绍一下如何在Spring Boot中整合并且使用Thymeleaf。

添加Thymeleaf依赖

想要使用Thymeleaf必须要要在POM文件中添加Thymeleaf相关的配置依赖,如下所示。

Spring Boot整合Thymeleaf模板引擎的详细教程

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

引入spring-boot-starter-thymeleaf之后,Spring Boot会默认自动对Thymeleaf进行配置,当时我们也可以通过配置文件对相关的基础配置进行调整,如下所示。

# Thymeleaf 相关配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.cache=false
  • prefix 指定模板文件的位置。
  • suffix 指定模板文件的后缀。
  • cache=false 在开发阶段关闭缓存,以便实时更新页面。

创建Thymeleaf模板

配置完成之后,接下来就是需要创建一个Thymeleaf的模板,如下所示,在src/main/resources/templates下创建一个命名为 index.html的HTML文件

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Welcome</title>
</head>
<body>
    <h1>Welcome to Thymeleaf!</h1>
    <p th:text="'Current time: ' + ${currentTime}"></p>
</body>
</html>

编写控制器

接下来就是通过Controller控制器来返回数据到模板中然后进行动态的HTML渲染操作,如下所示。

@Controller
public class HomeController {

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("currentTime", LocalDateTime.now());
        return "index"; // 返回 templates/index.html
    }
}

在上述代码中:

  • Model 用于向模板传递数据。
  • return "index" 告诉框架渲染 index.html。

接下来我们运行项目尝试访问http://localhost:8080,就会看到对应的页面中展示的内容。

Thymeleaf 的核心语法

变量表达式

通过th:text属性,我们可以设置文本的内容,如下所示。

<p th:text="'Hello, ' + ${name}"></p>

条件渲染

通过th:if 和 th:unless,我们可以进行条件渲染操作,根据不同的条件来渲染不同的页面显示效果,如下所示。

<div th:if="${showWelcome}">Welcome!</div>
<div th:unless="${showWelcome}">Goodbye!</div>

循环

通过th:each,我们可以实现基于列表数据的渲染操作,如下所示。

<ul>
    <li th:each="item : ${items}" th:text="${item}"></li>
</ul>

配置静态资源

对于项目中依赖的静态文件,我们可以统一放在src/main/resources/static文件夹中,然后通过如下的方式来引入。

<link rel="stylesheet" th:href="@{/css/style.css}" />
<script th:src="@{/js/app.js}"></script>

总结

Thymeleaf 简洁直观,适合构建现代化的动态 Web 应用程序。通过上面的步骤,我们就可以在Spring Boot项目中实现与Thymeleaf模板引擎的整合。在实际开发中,还可以利用其扩展功能,如布局支持、国际化等,使开发更加高效。

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表