SpringBoot之Thymeleaf模板引擎实例分析

发布时间:2022-07-19 09:48:33 作者:iii
来源:亿速云 阅读:153

SpringBoot之Thymeleaf模板引擎实例分析

引言

在现代Web开发中,前后端分离的架构模式越来越流行,但在某些场景下,传统的服务器端渲染(SSR)仍然有其独特的优势。Spring Boot作为Java生态中最流行的微服务框架之一,提供了对多种模板引擎的支持,其中Thymeleaf因其强大的功能和易用性而备受开发者青睐。本文将深入探讨Thymeleaf模板引擎在Spring Boot中的应用,并通过实例分析其核心特性和使用方法。

1. Thymeleaf简介

1.1 什么是Thymeleaf?

Thymeleaf是一个现代化的服务器端Java模板引擎,适用于Web和独立环境。它能够处理HTML、XML、JavaScript、CSS甚至纯文本。Thymeleaf的主要目标是提供一种优雅且高度可维护的模板创建方式,同时保持与HTML5的高度兼容性。

1.2 Thymeleaf的特点

2. Spring Boot集成Thymeleaf

2.1 添加依赖

在Spring Boot项目中集成Thymeleaf非常简单,只需在pom.xml中添加相应的依赖即可:

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

2.2 配置Thymeleaf

Spring Boot默认已经配置了Thymeleaf,但我们可以通过application.propertiesapplication.yml文件进行自定义配置。以下是一些常用的配置项:

# 设置模板文件的位置
spring.thymeleaf.prefix=classpath:/templates/
# 设置模板文件的后缀
spring.thymeleaf.suffix=.html
# 启用模板缓存(生产环境建议开启)
spring.thymeleaf.cache=true
# 设置模板编码
spring.thymeleaf.encoding=UTF-8
# 设置模板模式
spring.thymeleaf.mode=HTML5

2.3 创建Thymeleaf模板

src/main/resources/templates目录下创建一个简单的HTML模板文件index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf示例</title>
</head>
<body>
    <h1 th:text="${message}">默认消息</h1>
</body>
</html>

2.4 创建Controller

接下来,我们创建一个Spring MVC控制器来处理请求并返回Thymeleaf模板:

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

@Controller
public class ThymeleafController {

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("message", "欢迎使用Thymeleaf!");
        return "index";
    }
}

2.5 运行项目

启动Spring Boot应用后,访问http://localhost:8080/,你将看到页面显示“欢迎使用Thymeleaf!”。

3. Thymeleaf核心语法

3.1 表达式

Thymeleaf支持多种表达式,用于在模板中动态地插入数据或控制逻辑。常见的表达式包括:

3.2 常用属性

Thymeleaf提供了一系列属性,用于在HTML标签中嵌入动态内容。以下是一些常用的属性:

3.3 示例

以下是一个使用Thymeleaf表达式的示例:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf示例</title>
</head>
<body>
    <h1 th:text="${message}">默认消息</h1>
    <p th:if="${user != null}" th:text="'用户: ' + ${user.name}">用户信息</p>
    <ul>
        <li th:each="item : ${items}" th:text="${item}">项目</li>
    </ul>
</body>
</html>

在这个示例中,我们使用了th:textth:ifth:each属性来动态地生成页面内容。

4. Thymeleaf高级特性

4.1 模板布局

Thymeleaf支持模板布局,允许我们定义可重用的模板片段。通过使用th:fragmentth:replace属性,我们可以轻松地实现模板的模块化。

4.1.1 定义模板片段

src/main/resources/templates/layout目录下创建一个布局模板layout.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>布局模板</title>
</head>
<body>
    <header th:fragment="header">
        <h1>网站标题</h1>
    </header>
    <div th:fragment="content">
        <p>默认内容</p>
    </div>
    <footer th:fragment="footer">
        <p>版权信息</p>
    </footer>
</body>
</html>

4.1.2 使用模板片段

在其他模板中,我们可以通过th:replace属性引用这些模板片段:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>使用布局模板</title>
</head>
<body>
    <div th:replace="~{layout/header :: header}"></div>
    <div th:replace="~{layout/content :: content}">
        <p>自定义内容</p>
    </div>
    <div th:replace="~{layout/footer :: footer}"></div>
</body>
</html>

4.2 表单处理

Thymeleaf提供了强大的表单处理功能,能够轻松地与Spring MVC的表单绑定机制集成。

4.2.1 表单绑定

以下是一个简单的表单绑定示例:

<form th:action="@{/submit}" th:object="${user}" method="post">
    <label for="name">姓名:</label>
    <input type="text" id="name" th:field="*{name}">
    <label for="email">邮箱:</label>
    <input type="email" id="email" th:field="*{email}">
    <button type="submit">提交</button>
</form>

在这个示例中,th:object属性用于绑定表单对象,th:field属性用于绑定表单字段。

4.2.2 表单验证

Thymeleaf还支持表单验证,能够显示验证错误信息:

<form th:action="@{/submit}" th:object="${user}" method="post">
    <label for="name">姓名:</label>
    <input type="text" id="name" th:field="*{name}">
    <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}">姓名错误</span>
    <label for="email">邮箱:</label>
    <input type="email" id="email" th:field="*{email}">
    <span th:if="${#fields.hasErrors('email')}" th:errors="*{email}">邮箱错误</span>
    <button type="submit">提交</button>
</form>

在这个示例中,th:errors属性用于显示字段的验证错误信息。

4.3 国际化

Thymeleaf内置了国际化支持,能够根据用户的语言环境动态地切换显示内容。

4.3.1 配置国际化资源文件

src/main/resources目录下创建messages.propertiesmessages_zh_CN.properties文件:

messages.properties:

welcome.message=Welcome to Thymeleaf!

messages_zh_CN.properties:

welcome.message=欢迎使用Thymeleaf!

4.3.2 使用国际化消息

在模板中使用#{...}表达式引用国际化消息:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>国际化示例</title>
</head>
<body>
    <h1 th:text="#{welcome.message}">默认消息</h1>
</body>
</html>

4.4 安全性

Thymeleaf提供了自动转义功能,能够防止XSS攻击。默认情况下,Thymeleaf会对所有动态内容进行HTML转义。

4.4.1 手动转义

如果你需要手动控制转义行为,可以使用th:utext属性:

<p th:utext="${htmlContent}">HTML内容</p>

在这个示例中,th:utext属性不会对内容进行HTML转义。

4.4.2 禁用转义

如果你需要完全禁用转义,可以使用th:inline="none"

<p th:inline="none">[[${htmlContent}]]</p>

在这个示例中,[[...]]语法用于插入未转义的内容。

5. 实例分析

5.1 用户管理系统

为了更好地理解Thymeleaf在Spring Boot中的应用,我们将通过一个简单的用户管理系统来演示其核心功能。

5.1.1 项目结构

src/main/java
└── com.example.demo
    ├── controller
    │   └── UserController.java
    ├── model
    │   └── User.java
    └── DemoApplication.java
src/main/resources
├── templates
│   ├── layout
│   │   └── layout.html
│   ├── user
│   │   ├── list.html
│   │   ├── form.html
│   │   └── view.html
│   └── index.html
├── messages.properties
└── application.properties

5.1.2 用户模型

package com.example.demo.model;

public class User {
    private Long id;
    private String name;
    private String email;

    // 省略getter和setter方法
}

5.1.3 用户控制器

package com.example.demo.controller;

import com.example.demo.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/users")
public class UserController {

    private List<User> users = new ArrayList<>();

    @GetMapping
    public String listUsers(Model model) {
        model.addAttribute("users", users);
        return "user/list";
    }

    @GetMapping("/add")
    public String showAddForm(Model model) {
        model.addAttribute("user", new User());
        return "user/form";
    }

    @PostMapping
    public String addUser(@ModelAttribute User user) {
        user.setId((long) (users.size() + 1));
        users.add(user);
        return "redirect:/users";
    }

    @GetMapping("/{id}")
    public String viewUser(@PathVariable Long id, Model model) {
        User user = users.stream()
                .filter(u -> u.getId().equals(id))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("用户不存在"));
        model.addAttribute("user", user);
        return "user/view";
    }
}

5.1.4 用户列表模板

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户列表</title>
</head>
<body>
    <h1>用户列表</h1>
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>姓名</th>
                <th>邮箱</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="user : ${users}">
                <td th:text="${user.id}">1</td>
                <td th:text="${user.name}">张三</td>
                <td th:text="${user.email}">zhangsan@example.com</td>
                <td>
                    <a th:href="@{/users/{id}(id=${user.id})}">查看</a>
                </td>
            </tr>
        </tbody>
    </table>
    <a th:href="@{/users/add}">添加用户</a>
</body>
</html>

5.1.5 用户表单模板

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>添加用户</title>
</head>
<body>
    <h1>添加用户</h1>
    <form th:action="@{/users}" th:object="${user}" method="post">
        <label for="name">姓名:</label>
        <input type="text" id="name" th:field="*{name}">
        <label for="email">邮箱:</label>
        <input type="email" id="email" th:field="*{email}">
        <button type="submit">提交</button>
    </form>
</body>
</html>

5.1.6 用户详情模板

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户详情</title>
</head>
<body>
    <h1>用户详情</h1>
    <p>ID: <span th:text="${user.id}">1</span></p>
    <p>姓名: <span th:text="${user.name}">张三</span></p>
    <p>邮箱: <span th:text="${user.email}">zhangsan@example.com</span></p>
    <a th:href="@{/users}">返回列表</a>
</body>
</html>

5.2 运行效果

启动Spring Boot应用后,访问http://localhost:8080/users,你将看到一个简单的用户管理系统。你可以添加、查看用户信息,并且所有操作都是通过Thymeleaf模板动态生成的。

6. 总结

Thymeleaf作为Spring Boot中常用的模板引擎,提供了强大的功能和灵活的配置选项。通过本文的介绍和实例分析,我们了解了如何在Spring Boot项目中集成和使用Thymeleaf,并掌握了其核心语法和高级特性。希望本文能够帮助你在实际项目中更好地应用Thymeleaf,提升开发效率和代码质量。

7. 参考资料


通过本文的学习,你应该已经掌握了Thymeleaf在Spring Boot中的基本用法和高级特性。在实际项目中,你可以根据需求灵活运用这些知识,构建出高效、可维护的Web应用。

推荐阅读:
  1. SpringBoot 之Thymeleaf模板
  2. springBoot(5):web开发-模板引擎FreeMarker与thymeleaf

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot thymeleaf

上一篇:微信小程序实现选项卡的代码怎么写

下一篇:怎么利用pixi.js制作简单的跑酷小游戏

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》