对于个人站长来说,搭建动态网站时需要选择高效且易于维护的前端渲染技术。在Spring Boot生态中,Thymeleaf因其“自然模板”的特性(即模板可以直接在浏览器中打开且不破坏原有HTML结构)而广受欢迎。
本篇文章将指导您如何在新的Spring Boot项目中快速集成Thymeleaf,并通过一个简单的实例实现后端数据到前端页面的动态展示。
准备工作
确保您已经安装了Java环境(推荐JDK 17+)和Maven,并且有一个基础的Spring Boot项目。
第一步:添加Thymeleaf依赖
如果您使用Spring Initializr创建项目,请确保勾选了Spring Web和Thymeleaf。
如果您是手动配置,请在pom.xml中添加以下依赖:
<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>
第二步:创建Spring MVC控制器
我们将创建一个简单的Controller,它处理根路径请求(/),并将一些数据模型(Model)传递给视图。
创建一个名为HomeController.java的文件:
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
/**
* 处理根路径请求,并将数据传递给"index"视图
* @param model 用于存储传递给视图的数据
* @return 视图名称 (对应 src/main/resources/templates/index.html)
*/
@GetMapping("/")
public String home(Model model) {
// 放入一个变量到模型中
model.addAttribute("siteName", "站长技术分享");
model.addAttribute("welcomeMessage", "欢迎来到我的Spring Boot建站示例!");
// 返回的字符串 "index" 会被Thymeleaf解析器定位到 index.html
return "index";
}
}
第三步:创建Thymeleaf模板文件
Spring Boot默认会在 src/main/resources/templates/ 目录下查找模板文件。
创建文件:src/main/resources/templates/index.html。注意,我们需要在标签中声明Thymeleaf的命名空间。
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<!-- 使用 th:text 属性动态设置网页标题 -->
<title th:text="${siteName}">默认网站标题</title>
</head>
<body>
<header>
<h1 th:text="${welcomeMessage}">欢迎信息占位符</h1>
</header>
<section>
<p>这是使用Spring Boot和Thymeleaf模板引擎渲染的动态内容。</p>
<!-- 演示如何使用Thymeleaf内置工具类显示当前时间 -->
<p>页面渲染时间:
<span th:text="${#dates.format(#dates.createNow(), 'yyyy年MM月dd日 HH:mm:ss')}">
2024-01-01 12:00:00
</span>
</p>
</section>
</body>
</html>
第四步:运行与验证
启动您的Spring Boot应用(通常运行主类即可)。
在浏览器中访问 http://localhost:8080/。
您应该能看到页面显示了我们在HomeController中设置的“站长技术分享”作为标题,并且“欢迎来到我的Spring Boot建站示例!”作为主标题,同时显示了当前的服务器时间。
总结
通过以上简单的步骤,您已经成功地在Spring Boot中集成了Thymeleaf,并学会了如何利用Model对象从后端向前端模板传递数据。Thymeleaf是构建高性能、易于维护的动态网站界面的强大工具,特别适合个人站长在公有云VPS或虚拟机上部署应用。
汤不热吧