Thymeleaf基本使用,十位互联网一线高工手写Java高级知识

Thymeleaf是用来开发Web和独立环境项目的现代服务器端Java模板引擎,既适用于 web 环境,也适用于独立环境,比较适合当前的人员分工问题。其能够处理HTML、XML、JavaScript、CSS 甚至纯文本。提供了一种优雅且高度可维护的模板创建方法,可以直接在浏览器中正确显示,也可以作为静态原型方便开发团队协作。

Thymeleaf特点:

  • 动静结合: Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。

    Thymeleaf支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。

  • 开箱即用: Thymeleaf提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。

  • 多方言支持: Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

  • 与SpringBoot完美整合,SpringBoot提供了Thymeleaf的默认配置,并且为Thymeleaf设置了视图解析器,我们可以像操作jsp一样来操作Thymeleaf。代码几乎没有任何区别,就是在模板语法上有区别。

环境准备


使用Spring Initializr快速创建一个工程:

在这里插入图片描述

在这里插入图片描述

勾选web和Thymeleaf的依赖:

在这里插入图片描述

项目结构:

在这里插入图片描述

pom.xml:


<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-parent</artifactId>

        <version>2.3.9.RELEASE</version>

        <relativePath/> <!-- lookup parent from repository -->

    </parent>

    <groupId>com.ly</groupId>

    <artifactId>thymeleaf</artifactId>

    <version>0.0.1-SNAPSHOT</version>

    <name>thymeleaf</name>

    <description>Demo project for Spring Boot</description>

    <properties>

        <java.version>1.8</java.version>

    </properties>

    <dependencies>

        <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>



        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-test</artifactId>

            <scope>test</scope>

            <exclusions>

                <exclusion>

                    <groupId>org.junit.vintage</groupId>

                    <artifactId>junit-vintage-engine</artifactId>

                </exclusion>

            </exclusions>

        </dependency>

    </dependencies>



    <build>

        <plugins>

            <plugin>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-maven-plugin</artifactId>

            </plugin>

        </plugins>

    </build>



</project> 

Thymeleaf默认会开启页面缓存,提高页面并发能力。但会导致我们修改页面不会立即被展现,因此我们关闭缓存。


# 关闭Thymeleaf的缓存

spring:

  thymeleaf:

    cache:

      false 

另外,修改完毕页面,需要使用快捷键:Ctrl + Shift + F9来刷新工程。

在这里插入图片描述

快速入门


我们准备一个controller,控制视图跳转:


@Controller

public class HelloController {



    @GetMapping("hello")

    public String show1(Model model){

        model.addAttribute("msg", "Hello, Thymeleaf!");

        return "index";

    }

} 

新建一个html模板:

语法说明:

Thymeleaf通过${}来获取model中的变量,注意这不是el表达式,而是ognl表达式,但是语法非常像。不过区别在于,我们的表达式写在一个名为:th:text的标签属性中,这个叫做指令


<!DOCTYPE html>

<!--把html 的名称空间,改成:xmlns:th="http://www.thymeleaf.org" 会有语法提示-->

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

<head>

    <meta charset="UTF-8">

    <title>hello</title>

</head>

<body>

	<h1 th:text="${msg}">大家好</h1>

</body>

</html> 

启动项目,访问页面:

在这里插入图片描述

动静结合:

Thymeleaf崇尚自然模板,意思就是模板是纯正的html代码,脱离模板引擎,在纯静态环境也可以直接运行。现在如果我们直接在html中编写 ${}这样的表达式,显然在静态环境下就会出错,这不符合Thymeleaf的理念。

Thymeleaf中所有的表达式都需要写在指令中,指令是HTML5中的自定义属性,在Thymeleaf中所有指令都是以th:开头。因为表达式${user.name}是写在自定义属性中,因此在静态环境下,表达式的内容会被当做是普通字符串,浏览器会自动忽略这些指令,这样就不会报错了!

th常用标签


| 标签 | 作用 | 样例 |

| — | — | — |

| th:id | 替换id | <input th:id="${user.id}"/> |

| th:text | 文本替换 | <p text:="${user.name}">name</p> |

| th:utext | 支持html的文本替换 | <p utext:="${htmlcontent}">content</p> |

| th:object | 替换对象 | <div th:object="${user}"></div> |

| th:value | 属性赋值 | <input th:value="${user.name}" > |

| th:with | 变量赋值运算 | <div th:with="isEven=${user.age}%2==0"></div> |

| th:style | 设置样式 | th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''" |

| th:src | 替换资源 | <script type="text/javascript" th:src="@{index.js}"></script> |

| th:onclick | 点击事件 | th:onclick="'getCollect()'" |

| th:href | 替换超链接 | <a th:href="@{index.html}">url</a> |

| th:each | 迭代 | <tr th:each="student:${user}" > |

| th:if | 判断条件 | <a th:if="${userId == collect.userId}" > |

| th:unless | 和th:if判断相反 | <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:inline | 定义js脚本可以使用变量 | <script type="text/javascript" th:inline="javascript"> |

| th:action | 表单提交的地址 | <form action="subscribe.html" th:action="@{/subscribe}"> |

| th:remove | 删除某个属性 | <tr th:remove="all"> all:删除所有的孩子、body:删除其所有的孩子,不包含标签、tag:删除标签、all-but-first:删除除第一个以外的所有、none:什么也不做 |

变量


新建一个实体类:User


public class User {

    

    private String name;

    private int age;

	private boolean sex;

    private String role;

    //Get、Set

} 

然后在模型中添加数据


@GetMapping("add")

public String addUser(Model model){

    User user = new User();

    user.setAge(21);

    user.setName("<font color='red'>小明</font>");

    

    model.addAttribute("user", user);

    return "user";

} 

th:text指令出于安全考虑,会把表达式读取到的值进行处理,防止html的注入。例如,<p>你好</p>将会被格式化输出为$lt;p$gt;你好$lt;/p$lt;如果想要不进行格式化输出,而是要输出原始内容,则使用th:utext来代替.

示例:我们在页面获取user数据:


<h1>

    欢迎您:<span th:utext="${user.name}">---</span>

</h1> 

效果:

在这里插入图片描述

ognl表达式的语法糖:

刚才获取变量值,我们使用的是经典的对象.属性名方式。但有些情况下,我们的属性名可能本身也是变量,怎么办?ognl提供了类似js的语法方式:

例如:${user.name} 可以写作${user['name']}

自定义变量


看下面的案例:


<h2>

    <p>Name: <span th:text="${user.name}">Jack</span>.</p>

    <p>Age: <span th:text="${user.age}">21</span>.</p>

</h2> 

我们获取用户的所有信息,分别展示。当数据量比较多的时候,频繁的写user.就会非常麻烦。因此,Thymeleaf提供了自定义变量来解决:


<h2 th:object="${user}">

    <p>Name: <span th:text="*{name}">Jack</span>.</p>

    <p>Age: <span th:text="*{age}">21</span>.</p>

</h2> 

  • 首先在 h2上 用 th:object="${user}"获取user的值,并且保存

  • 然后,在h2内部的任意元素上,可以通过 *{属性名}的方式,来获取user中的属性,这样就省去了大量的user.前缀了

方法调用


ognl表达式本身就支持方法调用,例如:


<h2 th:object="${user}">

    <p>FirstName: <span th:text="*{name.split(' ')[0]}">first</span>.</p>

    <p>LastName: <span th:text="*{name.split(' ')[1]}">last</span>.</p>

</h2> 

这里我们调用了name(是一个字符串)的split方法。

Thymeleaf内置对象

Thymeleaf中提供了一些内置对象,并且在这些对象中提供了一些方法,方便我们来调用。获取这些对象,需要使用#对象名来引用。

环境相关对象:

| 对象 | 作用 |

| :-: | :-- |

| #ctx | 获取Thymeleaf自己的Context对象 |

| #requset | 如果是web程序,可以获取HttpServletRequest对象 |

| #response | 如果是web程序,可以获取HttpServletReponse对象 |

| #session | 如果是web程序,可以获取HttpSession对象 |

| #servletContext | 如果是web程序,可以获取HttpServletContext对象 |

Thymeleaf提供的全局对象:

| 对象 | 作用 |

| :-: | :-- |

| #dates | 处理java.util.date的工具对象 |

| #calendars | 处理java.util.calendar的工具对象 |

| #numbers | 用来对数字格式化的方法 |

| #strings | 用来处理字符串的方法 |

| #bools | 用来判断布尔值的方法 |

| #arrays | 用来护理数组的方法 |

| #lists | 用来处理List集合的方法 |

| #sets | 用来处理set集合的方法 |

| #maps | 用来处理map集合的方法 |

  • 举例

我们在环境变量中添加日期类型对象


@GetMapping("date")

public String date(Model model){

    model.addAttribute("today", new Date());

    return "date";

} 

在页面中处理


<p>

    今天是: <span th:text="${#dates.format(today,'yyyy-MM-dd')}">2020-03-30</span>

</p> 

效果:

在这里插入图片描述

字面值


有的时候,我们需要在指令中填写基本类型如:字符串、数值、布尔等,并不希望被Thymeleaf解析为变量,这个时候称为字面值。

字符串字面值:

使用一对'引用的内容就是字符串字面值了:


<h1 th:text="'${msg}'">大家好</h1> 

th:text中的${msg}并不会被认为是变量,而是一个字符串:

在这里插入图片描述

数字字面值:

数字不需要任何特殊语法, 写的什么就是什么,而且可以直接进行算术运算


<p>今年是 <span th:text="2021">1999</span>.</p>

<p>两年后将会是 <span th:text="2021 + 2">2001</span>.</p> 

在这里插入图片描述

布尔字面值:

布尔类型的字面值是true或false:


<div th:if="true">

    你填的是true

</div> 

这里引用了一个th:if指令,跟vue中的v-if类似

拼接


我们经常会用到普通字符串与表达式拼接的情况:


<span th:text="'欢迎您:' + ${user.name} + '!'"></span> 

字符串字面值需要用'',拼接起来非常麻烦,Thymeleaf对此进行了简化,使用一对|即可:


<span th:utext="|欢迎您:${user.name}!|"></span> 

与上面是完全等效的,这样就省去了字符串字面值的书写。

在这里插入图片描述

运算


需要注意:${}内部的是通过OGNL表达式引擎解析的,外部的才是通过Thymeleaf的引擎解析,因此运算符尽量放在${}外进行,例如: <span th:text="${user.age}+2"></span>

算术运算:

支持的算术运算符:+ - * / %

比较运算:

支持的比较运算:>, <, >= , <= ,但是>, <不能直接使用,因为xml会解析为标签,要使用别名。

注意 == and !=不仅可以比较数值,类似于equals的功能。

可以使用的别名:gt (>), lt (<), ge (>=), le (<=), not (!). Also eq (==), neq/ne (!=).

三元运算:


<span th:text="${user.sex} ? '男':'女'"></span> 

三元运算符的三个部分:conditon ? then : else

  • condition:条件

  • then:条件成立的结果

  • else:不成立的结果

其中的每一个部分都可以是Thymeleaf中的任意表达式。有的时候,我们取一个值可能为空,这个时候需要做非空判断,可以使用 表达式 ?: 默认值简写: <span th:text="${user.name} ?: '小红' "></span>,当前面的表达式值为null时,就会使用后面的默认值。 注意:?:之间没有空格。

循环


循环也是非常频繁使用的需求,我们使用th:each指令来完成:

假如有用户的集合:users在Context中。


<tr th:each="user : ${users}"> 

    <td th:text="${user.name}">name</td>

    <td th:text="${user.age}">age</td>

</tr> 

  • ${users} 是要遍历的集合,可以是以下类型:

    • Iterable,实现了Iterable接口的类

    • Enumeration,枚举

    • Interator,迭代器

    • Map,遍历得到的是Map.Entry

    • Array,数组及其它一切符合数组结果的对象

在迭代的同时,我们也可以获取迭代的状态对象:


<tr th:each="user,stat : ${users}">

    <td th:text="${user.name}">name</td>

    <td th:text="${user.age}">age</td>

</tr> 

stat对象包含以下属性:

  • index,从0开始的角标

  • count,元素的个数,从1开始

  • size,总元素个数

最后

面试题文档来啦,内容很多,485页!

由于笔记的内容太多,没办法全部展示出来,下面只截取部分内容展示。

CodeChina开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频】

1111道Java工程师必问面试题

MyBatis 27题 + ZooKeeper 25题 + Dubbo 30题:

Elasticsearch 24 题 +Memcached + Redis 40题:

Spring 26 题+ 微服务 27题+ Linux 45题:

Java面试题合集:

*   Map,遍历得到的是Map.Entry

*   Array,数组及其它一切符合数组结果的对象

在迭代的同时,我们也可以获取迭代的状态对象:


<tr th:each="user,stat : ${users}">

    <td th:text="${user.name}">name</td>

    <td th:text="${user.age}">age</td>

</tr> 

stat对象包含以下属性:

  • index,从0开始的角标

  • count,元素的个数,从1开始

  • size,总元素个数

最后

面试题文档来啦,内容很多,485页!

由于笔记的内容太多,没办法全部展示出来,下面只截取部分内容展示。

CodeChina开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频】

1111道Java工程师必问面试题

[外链图片转存中…(img-tdmQ03sm-1630844336397)]

MyBatis 27题 + ZooKeeper 25题 + Dubbo 30题:

[外链图片转存中…(img-8VhyPDgx-1630844336398)]

Elasticsearch 24 题 +Memcached + Redis 40题:

[外链图片转存中…(img-1bYGbOLX-1630844336400)]

Spring 26 题+ 微服务 27题+ Linux 45题:

[外链图片转存中…(img-0DC3qWSH-1630844336401)]

Java面试题合集:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值