【Spring实战】12 Thymeleaf

文章目录

1. 定义

Thymeleaf 是一个用于在 Web 应用程序中进行服务器端 Java 模板渲染的 Java 库。它是一种用于构建 Web 应用程序的++模板引擎++,专注于生成可在浏览器中正确显示的 HTML。

2. 设计目标

Thymeleaf 的设计目标之一是使模板更容易与浏览器中的原始 HTML 一起查看,这样即使在没有模板引擎的情况下,也可以正确地显示。

3. 官网

https://www.thymeleaf.org/

4. Spring 集成 Thymeleaf

1)添加依赖

在生成的项目中,确保在 pom.xml 文件中有 Thymeleaf 的依赖。

如下所示

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

这个依赖将包含 Spring Boot 对 Thymeleaf 的自动配置

2)创建模版

src/main/resources/templates 目录下创建 Thymeleaf 模板文件。

例如,创建一个名为 index.html 的文件

存放路径:src/main/resources/templates/index.html

html 复制代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Spring Demo</title>
    </head>
    <body>
        <h1 th:text="${msg}"></h1>
    </body>
</html>

这个简单的模板包含一个使用 Thymeleaf 表达式的标题,${msg} 处会显示 Java 后台给我传回来的信息

3)创建Controller

创建一个简单的控制器类,用于处理页面请求:

复制代码
package com.cheney.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {

    @GetMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("msg", "Hello Thymeleaf");
        return "index";
    }
}

这个控制器有一个 hello 方法,该方法通过 Model 将消息传递给 Thymeleaf 模板,并返回模板的名称,并且会将 "Hello Thymeleaf" 携带到 HTML 为 ${msg} 赋值,再通过 HTML 自己去渲染。

4)启动程序

5)执行验证

使用浏览器访问如下的 URL,就能够看到一个包含 Thymeleaf 表达式的页面啦

http://localhost:8080/hello

5. 代码详细

https://github.com/cheney09/spring-practical-combat/tree/main/12/demo

总结

至此,就已经成功的使用 Spring Boot 集成了 Thymeleaf 模版引擎并创建了一个简单的动态 Web 应用程序。这仅仅是一个入门级的例子,Thymeleaf 提供了丰富的功能,包括表达式、条件语句、迭代等,使你能够更灵活地构建复杂的页面。希望这篇博客能帮助你走入 Thymeleaf 的大门。

相关推荐
budingxiaomoli7 小时前
Spring IoC &DI
java·spring·ioc·di
Spider Cat 蜘蛛猫7 小时前
Springboot SSO系统设计文档
java·spring boot·后端
未若君雅裁7 小时前
MySQL高可用与扩展-主从复制读写分离分库分表
java·数据库·mysql
学习中.........7 小时前
从扰动函数的变化,感受红黑树带来的性能提升
java
计算机安禾7 小时前
【c++面向对象编程】第24篇:类型转换运算符:自定义隐式转换与explicit
java·c++·算法
zyk_computer8 小时前
AI 时代,或许 Rust 比 Python 更合适
人工智能·后端·python·ai·rust·ai编程·vibe coding
weixin199701080168 小时前
【保姆级教程】淘宝/天猫商品详情 API(item_get)接入指南:Python/Java/PHP 调用示例与 JSON 返回值解析
java·python·php
环流_8 小时前
redis核心数据类型在java中的操作
java·数据库·redis
雨辰AI8 小时前
SpringBoot3 项目国产化改造完整流程|从 MySQL 到人大金仓落地
java·数据库·后端·mysql·政务
带刺的坐椅8 小时前
Java 流程编排新范式 Solon Flow:一个引擎,七种节点,覆盖规则/任务/工作流/AI 编排全场景
java·spring·ai·solon·flow