Springboot中如何使用thymeleaf

发布时间:2021-07-30 17:27:51 作者:Leah
来源:亿速云 阅读:453
# SpringBoot中如何使用Thymeleaf

## 一、Thymeleaf简介

### 1.1 什么是Thymeleaf
Thymeleaf是一款现代化的服务器端Java模板引擎,适用于Web和独立环境。与JSP不同,Thymeleaf模板是纯HTML文件,可以直接在浏览器中打开并显示静态原型,同时又能被服务器端引擎解析处理。

### 1.2 主要特点
- **自然模板**:支持HTML5标准,无需特殊标签
- **Spring生态完美集成**:官方推荐的Spring MVC模板引擎
- **表达式语言**:强大的OGNL/SpringEL表达式支持
- **模块化设计**:包含文本、HTML、XML、JavaScript等模板类型

## 二、SpringBoot集成Thymeleaf

### 2.1 添加依赖
在`pom.xml`中添加starter依赖:

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

2.2 自动配置原理

SpringBoot自动配置类ThymeleafAutoConfiguration会: 1. 默认模板路径:classpath:/templates/ 2. 默认后缀:.html 3. 默认编码:UTF-8 4. 开启模板缓存(生产环境)

可通过application.properties修改配置:

# 关闭模板缓存(开发建议)
spring.thymeleaf.cache=false
# 修改模板前缀
spring.thymeleaf.prefix=classpath:/views/

三、基础语法详解

3.1 命名空间

模板文件需添加命名空间:

<html xmlns:th="http://www.thymeleaf.org">

3.2 常用属性

属性 说明 示例
th:text 文本替换 <span th:text="${message}">默认文本</span>
th:utext 非转义HTML <div th:utext="${htmlContent}"></div>
th:value 表单值绑定 <input th:value="${user.name}">
th:each 循环遍历 <tr th:each="item : ${list}">
th:if 条件判断 <div th:if="${not #lists.isEmpty(items)}">

3.3 表达式类型

  1. 变量表达式${...}
    
    <p th:text="${user.email}">user@example.com</p>
    
  2. 选择表达式*{...}
    
    <div th:object="${user}">
     <p th:text="*{name}">默认名称</p>
    </div>
    
  3. 消息表达式#{...}
    
    <h1 th:text="#{page.title}">默认标题</h1>
    
  4. 链接表达式@{...}
    
    <a th:href="@{/user/{id}(id=${userId})}">个人主页</a>
    

四、实战开发示例

4.1 控制器编写

@Controller
public class UserController {
    
    @GetMapping("/users")
    public String listUsers(Model model) {
        List<User> users = Arrays.asList(
            new User(1, "张三", "zhangsan@example.com"),
            new User(2, "李四", "lisi@example.com")
        );
        model.addAttribute("users", users);
        return "user/list"; // 对应templates/user/list.html
    }
}

4.2 模板开发

templates/user/list.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>用户列表</title>
    <meta charset="UTF-8">
</head>
<body>
    <h1 th:text="#{user.list.title}">用户列表</h1>
    
    <table class="table">
        <thead>
            <tr>
                <th>ID</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}">test@example.com</td>
            </tr>
        </tbody>
    </table>
    
    <!-- 分页组件 -->
    <div th:if="${users.totalPages > 1}">
        <span th:each="i : ${#numbers.sequence(1, users.totalPages)}">
            <a th:href="@{/users(page=${i})}" 
               th:text="${i}" 
               th:class="${i == users.number + 1} ? 'current' : ''">1</a>
        </span>
    </div>
</body>
</html>

五、高级功能

5.1 布局模板

使用th:fragment定义可重用片段:

templates/layout/base.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="common-header">
    <meta charset="UTF-8">
    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
</head>
<body>
    <div th:fragment="header">
        <!-- 公共头部 -->
    </div>
    
    <div th:fragment="footer">
        <!-- 公共底部 -->
    </div>
</body>
</html>

子模板引用:

<html th:replace="~{layout/base :: common-header}">
<div th:replace="~{layout/base :: header}"></div>

5.2 表单处理

<form th:action="@{/users}" th:object="${user}" method="post">
    <input type="text" th:field="*{name}" 
           class="form-control" placeholder="姓名">
    <input type="email" th:field="*{email}"
           class="form-control" placeholder="邮箱">
    <button type="submit" class="btn btn-primary">提交</button>
</form>

5.3 国际化支持

  1. 创建消息文件messages.properties:
    
    user.list.title=用户列表
    button.submit=提交
    
  2. 模板中使用:
    
    <h1 th:text="#{user.list.title}"></h1>
    <button th:text="#{button.submit}"></button>
    

六、调试与优化

6.1 开发工具配置

  1. 开启开发模式:
    
    spring.thymeleaf.cache=false
    spring.thymeleaf.mode=HTML
    
  2. 使用LiveReload实现热更新

6.2 常见问题解决

  1. 模板不生效

    • 检查文件是否放在templates目录
    • 确认Controller返回的视图名称匹配
  2. 静态资源404

    <!-- 正确引用方式 -->
    <link th:href="@{/css/style.css}" rel="stylesheet">
    

七、最佳实践建议

  1. 模板组织原则

    • 按功能模块分目录存放
    • 公共片段提取到common目录
    • 命名遵循模块名/功能名.html格式
  2. 性能优化

    • 生产环境务必开启缓存
    • 避免在模板中进行复杂计算
    • 合理使用th:if替代th:unless
  3. 安全注意事项

    • 对用户输入内容使用th:text自动转义
    • 谨慎使用th:utext
    • 表单添加CSRF防护

结语

Thymeleaf作为SpringBoot官方推荐的模板引擎,通过本文介绍的基础语法和实战技巧,开发者可以快速构建动态Web页面。其自然模板特性使得前后端协作更加高效,结合SpringBoot的自动配置能力,让JavaWeb开发变得简单而优雅。

提示:SpringBoot 3.x版本建议使用Thymeleaf 3.1+版本以获得更好的性能表现 “`

推荐阅读:
  1. 如何在SpringBoot中使用thymeleaf方法
  2. Thymeleaf怎么在SpringBoot中使用

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

spring boot thymeleaf

上一篇:CentOS Linux下怎么修复bash漏洞

下一篇:怎么用Shell脚本实现监控iptables规则是否被修改

相关阅读

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

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