柏竹 柏竹
首页
后端
前端
  • 应用推荐
关于
友链
  • 分类
  • 标签
  • 归档

柏竹

奋斗柏竹
首页
后端
前端
  • 应用推荐
关于
友链
  • 分类
  • 标签
  • 归档
  • Java基础

  • JavaWeb

  • 拓展技术

  • 框架技术

  • 数据库

  • 数据结构

  • Spring

  • SpringMVC

  • SpringBoot

    • SpringBoot
    • SpringBoot3基础特性
    • SpringBoot3核心原理
    • 框架整合

      • SpringBoot SpringMVC 整合
      • SpringBoot JDBC 整合
      • SpringBoot MyBatis 整合
      • SpringBoot tk-MyBatis 整合
      • SpringBoot Shiro 整合
      • SpringBoot Redis 整合
      • SpringBoot MyBatisPlus 整合
      • SpringBoot JSON 整合
      • SpringBoot Thymeleaf 整合
        • Thymeleaf 整合
          • 表达式
          • 变量表达式
          • 选择表达式
          • URL表达式
          • th属性
          • 内置对象
          • 首次应用
      • 整合WebSocket实现聊天功能
    • SpringBoot部署
  • SpringClound

  • Ruoyi-Vue-Plus

  • 后端
  • SpringBoot
  • 框架整合
Bozhu12
2023-06-10
目录

SpringBoot Thymeleaf 整合

# Thymeleaf 整合

Thymeleaf是用于 Web 和 独立环境 的Java模板引擎(类似于JSP)

SpringBoot 为 Thymeleaf 提供一系列的默认配置,Thymeleaf依赖 一旦导入,项目会自动配置

优点:

  • Thymeleaf 在有网络和无网络的环境下皆可运行,通过美工实现页面数据的动静结合 有网络则覆盖静态显示的内容数据 无网络则显示默认静态的内容数据
  • SpringBoot完美整合,springboot默认整合thymeleaf

# 表达式

Thymeleaf有3表达式

  • 变量表达式${...}
  • 选择表达式*{...}
  • URL表达式@{...}

# 变量表达式

==${...}== 变量表达式可以直接过去域中的数据。接收方式和JSP一样,但使用呈现方式不一样

示例:(后端响应变量 "good" : "Thymeleaf very Good!")

<!--响应的变量 good的值为 “Thymeleaf very Good!” -->
<h5>表达式</h5>
<span>${good}</span><br>
<span th:text="${good}">你好 thymleaf</span><br>
<span>${good}</span><br>

<!-- 结果预览
表达式
${good}
Thymeleaf very Good!
${good}
-->

# 选择表达式

==*{...}== 选择表达式 也称 星号表达式,不过这一操作需要预先通过选择一个对象进行充当上下文容器的变量执行

示例:(后端响应变量 {"cat" : "猫","dog" : "狗"})

<div th:object="${pet}">
    <span th:text="*{dog}"></span> <br>
    <span th:text="*{cat}"></span> <br>
</div>

<!-- 浏览器预览结果
狗
猫
-->

# URL表达式

URL表达式 是把一个有效的信息 添加到URL,也是URL重写

重写形式有3种:

  • url表达式
  • 文本替换
  • 字符串拼接
<!-- url表达式 (无参
	结果:href="main.html" 
-->
<a th:href="@{/main}">

<!-- url表达式(有参
	后端响应:{user.id : 1,user.name : "张三"}
	结果:href="/del?id=1&name=张三" 
-->
<a th:href="@{/del(id=*{id},name=${user.name})}">删除</a>
    
<!-- 文本替换
	结果:href="/update/1" 
-->
<a th:href="@{|/update/*{id}|}">修改</a>

<!-- 字符串拼接
	 结果:href="/approve/1" 
-->
<a th:href="'/approve/'+*{id}">审核</a>

# th属性

关键字 功能介绍 案例
th:id 替换id <input th:id="'xxx' + ${collect.id}"/>
th:text 文本替换 <p th:text="${user.name}">张三</p>
th:utext 支持html的文本替换 <p th:utext="${htmlContent}">content</p>
th:object 替换对象 <div th:object="${user}">
th:value 属性赋值 <input th:value="${user.id}"/>
th:with 变量赋值运算 <div th:with="isEven=${prodStat.count}%2==0"></div>
th:style 设置样式 th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"
th:onclick 点击事件 th:onclick="'getCollect()'"
th:each 属性赋值 <tr th:each="user,userStat:${users}"/>
th:if 判断条件 <a th:if="${userId == collect.userId}" >
th:unless 和th:if判断相反 <a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
th:href 链接地址 <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> />
th:switch 多选择 配合th:case 使用 <div th:switch="${user.role}">
th:case th:switch的一个分支 <p th:case="'admin'">User is an administrator</p>
th:fragment 布局标签,定义一个代码片段,方便其它地方引用 <div th:fragment="alert">
th:include 布局标签,替换内容到引入的文件 <head th:include="layout :: htmlhead" th:with="title='xx'"></head> />
th:replace 布局标签,替换整个标签到引入的文件 <div th:replace="fragments/header :: title"></div>
th:selected selected选择框 选中 th:selected="(${xxx.id} == ${configObj.dd})"
th:src 图片类地址引入 <img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" />
th:inline 定义js脚本可以使用变量 <script type="text/javascript" th:inline="javascript">
th:action 表单提交的地址 <form action="subscribe.html" th:action="@{/subscribe}">
th:remove 删除某个属性 <tr th:remove="all">
1. all: 删除所有
2. body: 不删本身, 删除其所有的子标签
3. tag: 删除本身,但不删除它的子标签
4. all-but-first: 仅保留第一个子标签,其他删除
5. none: 什么也不做
th:attr 设置标签属性,多个属性可以用逗号分隔 <img th:attr="src=@{/image/aa.jpg},title=#{logo}"/> 一般比较少使用(难以阅读

常用th属性 示例:

条件判断 th:if/th:unless 判断属性是否成立,如果成立则显示

<!-- 响应:{"numbers":[1,2,3]} -->
<a th:if="${numbers.length > 0}">测试1</a><br>
<a th:if="${numbers.length <= 0}">测试2</a><br>
<a th:unless="${numbers.length <= 0}">测试3</a><br>

<!-- 预览结果
测试1

测试3
-->

for循环 th:each

组成拆解:==

...==

status状态对象的属性:

类型 status属性 说明
int index 迭代当前对象(从0开始)
int count 迭代当前对象(从1开始)
int size 被迭代的对象大小
- current 当前迭代变量
boolean even 当前迭代值 是否为 偶数
boolean odd 当前迭代值 是否为 奇数
boolean first 当前迭代值 是否为 第一个
boolean last 当前迭代值 是否为 最后一个
<!-- 
	响应:"users":[{
			"id":"1",
			"name":"张三",
			"userName":"zhangsan",
			"age":"23",
			"sex":1,
			"birthday":"1980-02-30"
		},...]
-->
<tr th:each="user ,status : ${users}" th:object="${user}">
    <td th:text="${status.count}">1</td>
    <td th:text="*{id}">233</td>
    <td data-th-text="*{name}">张三</td>
    <td th:text="${user.userName}">zhangsan</td>
    <td th:text="${user.age}">20</td>
    <td th:text="${user.sex} == 1 ? '男': '女'">男</td>
    <td th:text="${user.birthday}">1980-02-30</td>
    <td>
        <!--不同参数 形式-->
        <a th:href="@{/del(id=*{id},name=${user.name})}">删除</a>
        <!--文本替换 形式-->
        <a th:href="@{|/update/*{id}|}">修改</a>
        <!--字符串拼接 形式-->
        <a th:href="'/approve/'+*{id}">审核</a>
    </td>
</tr>

# 内置对象

Thymeleaf提供了一系列Utiliy对象,可直接通过#进行访问:

  • strings: 字符串工具对象,常用方法有:equals、equalsIgnoreCase、length、trim、toUpperCase、toLowerCase、indexOf、substring、replace、startsWith、endsWith,contains 和 containsIgnoreCase 等
  • numbers: 数字工具对象,常用的方法有:formatDecimal 等
  • bools: 布尔工具对象,常用的方法有:isTrue 和 isFalse 等
  • arrays: 数组工具对象,常用的方法有:toArray、length、isEmpty、contains 和 containsAll 等;
  • lists/sets: List/Set 集合工具对象,常用的方法有:toList、size、isEmpty、contains、containsAll 和 sort 等
  • maps: Map 集合工具对象,常用的方法有:size、isEmpty、containsKey 和 containsValue 等
  • dates: 日期工具对象,常用的方法有:format、year、month、hour 和 createNow 等
<h4>dates</h4>
<p th:text="${#dates.createNow()}">获取当前日期</p>
<p th:text="${#dates.format(#dates.createNow())}">日期格式化</p>
<p th:text="${#dates.format(#dates.createNow(),'yyyy-MM-dd HH:mm:ss')}">日期自定义格式化</p>
<!-- 预览结果
dates
Mon Sep 20 14:57:12 CST 2021
2021年9月20日 下午02时57分12秒
2021-09-20 14:57:12
-->

<!-- 响应:"good":"Thymeleaf very Good!"-->
<h4>strings</h4>
<p th:text="${#strings.substring(good, 6, 9)}">截取字符串</p>
<p th:text="${#strings.length(good)}">获得长度</p>
<p th:text="${#strings.randomAlphanumeric(6)}">随机字符串</p>
<p th:text="${#strings.equals(good, 'hello')}">比较</p>
<!--  预览结果
eaf
20
NI5QPI
false
-->

更多了解:Thymeleaf (opens new window) (19 Appendix B: Expression Utility Objects)

# 首次应用

前提说明:

  • 在 .html文件 需要添加以下的命名空间(否则无法识别 th属性标签 ==

    .... ==

  • 后端的 资源文件 需要存放指定目录 classpath:/templates/*

    默认前缀: templates/ 默认后缀: .html

  • 测试优化。在修改页面的时,由于缓存并非立即呈现效果,因此可通过添加以下全参关闭缓存

    # 开发阶段关闭 thymeleaf的模板缓存
    spring.thymeleaf.cache=false
    

应用步骤:

  1. 引入依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
  2. 创建前端文件。路径:==templates/ThymeleafView.html==

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <ul>
            <li th:each="user,userStat : ${userList}" th:object="${user}">
                <span th:text="*{id}"></span> ==
                <span th:text="*{name}"></span> ==
                <span th:text="${user.age}"></span>
            </li>
        </ul>
    </body>
    </html>
    
  3. 封装 User实体类

    public class User {
        String id;
        String name;
        int age;
        
        // 构造全参/无参 、set 、get方法省略。。。
    }
    
  4. 编辑 Controller控制器

    @Controller
    public class HelloController {
    
        @GetMapping("/findAll")
        public ModelAndView findAll() {
            ModelAndView view = new ModelAndView();
    
            List<User> list = new ArrayList<User>(){{
                add(new User("2","张三",33));
                add(new User("3","李四",34));
                add(new User("4","王五",35));
                add(new User("5","赵六",36));
            }};
    
            view.addObject("userList",list);
            view.setViewName("ThymeleafView");
            return view;
        }
    }
    
  5. 启动直接访问即可,结果示例

    <body>
        <ul>
            <li>
                <span>2</span> ==
                <span>张三</span> ==
                <span>33</span>
            </li>
            <li>
                <span>3</span> ==
                <span>李四</span> ==
                <span>34</span>
            </li>
            <li>
                <span>4</span> ==
                <span>王五</span> ==
                <span>35</span>
            </li>
            <li>
                <span>5</span> ==
                <span>赵六</span> ==
                <span>36</span>
            </li>
        </ul>
    </body>
    
#Thymeleaf

← SpringBoot JSON 整合 整合WebSocket实现聊天功能→

最近更新
01
HTTPS自动续签
10-21
02
博客搭建-简化版(脚本)
10-20
03
ruoyi-vue-plus-部署篇
07-13
更多文章>
Theme by Vdoing | Copyright © 2019-2024 | 桂ICP备2022009417号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式