SpringBoot学习笔记(四)——Thymeleaf模板

本文详细介绍了SpringBoot中如何使用Thymeleaf模板引擎,从基础概念到实战应用,涵盖Thymeleaf的表达式、属性、字面量、运算符等内容,并展示了在实际开发中的用例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、认识Themeleaf

Thymeleaf是使用Java开发的一个模板引擎,以HTML标签为载体,作为前端页的数据展示。
SpringBoot集成了Thymeleaf模板技术,并且官方也推荐使用该技术代替JSP。
官方手册:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
官方地址:https://www.thymeleaf.org/index.html

二、第一个例子

1、引入thymeleaf依赖

官方:
<dependency>
  <groupId>org.thymeleaf</groupId>
  <artifactId>thymeleaf</artifactId>
  <version>3.0.15.RELEASE</version>
</dependency>
springboot集成:
  <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
	</dependency>

2、编写controller

@Controller
public class HelloController {

    @GetMapping("/hello")
    public String  hello(HttpServletRequest request){
        request.setAttribute("msg","欢迎使用Thymeleaf!!!");
        //视图名称
        return "hello";
    }
}

3、在resources/template目录下,编写hello.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
<h3>使用Thymeleaf例子</h3>
//th:text=“${msg}”:使用request域中的msg替换标签中的文本数据。
<p th:text="${msg}">数据在这显示</p>
</body>
</html>

要注意,th命名空间为:http://www.thymeleaf.org
4、Thymeleaf配置体系
前缀:spring.thymeleaf
示例:

#数据缓存,默认是true 在开发阶段改为false,使修改立即生效
spring.thymeleaf.cache=false
#视图解析前缀,默认是classpath:/templates/
spring.thymeleaf.prefix=classpath:/templates/
#视图解析后缀,默认是.html
spring.thymeleaf.suffix=.html
#字符编码,默认是UTF-8
spring.thymeleaf.encoding=UTF-8
#模板类型,默认是HTML
spring.thymeleaf.mode=HTML

三、表达式

1、标准变量表达式
语法:${key}
作用:获取key对应的文本数据,key是request域中的key。对象:Model、request等
使用:在html标签中使用th:text="${key}"
示例:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>标准变量表达式</title>
</head>
<body>
    <h3>标准变量表达式:${key}</h3>
    <div>
        <p th:text="${site}">如果key不存在,则该标签为空标签</p>
        <br>
        <p>获取Student对象的值, key.属性名</p>
        <p th:text="${stu.id}">id</p> 
        <p th:text="${stu.name}">name</p>
        <p th:text="${stu.age}">age</p>
    </div>
</body>
</html>

2、选择变量表达式
语法:*{key}
说明:需要配合th:object一起使用。选择变量表达式,也叫星号变量表达式,使用th:object属性来绑定对象,选择表达式首先使用th:object来绑定后台传来的对象,然后使用" * "来代表这个对象,后面的{}中的值是此对象中的属性。选择变量表达式在执行时是在选择的对象上进行求解,而${key}是在上下文的变量model上求解。
目的:简单获取对象中的属性值
示例:

    <h3>标准变量表达式:*{key}</h3>
    <div th:object="${stu}">
        <p>获取Student对象的值</p>
        <p th:text="*{id}">id</p>
        <p th:text="*{name}">name</p>
        <p th:text="*{age}">age</p>
        <p>*{属性名}作用域在本div内</p>
    </div>
    <p th:text="*{stu.name}">也可以这么使用</p>

3、链接表达式(url表达式)
语法:@{链接url}
说明:主要用于链接、地址的展示。可用于<script:src="">、<a href="">、<form auction="">、<img src="">等。可以在URL路径中动态获取数据。
示例:

    <h3>链接变量表达式:@{url}</h3>
    <a th:href="@{http://www.baidu.com}">百度</a>
    <a th:href="@{/tpl/expression3}">expression3</a>
    <a th:href="@{'/tpl/queryStudent?id='+${id}}">获取model中的id</a>
    <p>推荐使用以下传参方式</p>
    <a th:href="@{/tpl/queryUser(name=${name},age=${age})}">获取model中的name,age</a>

四、Thymeleaf属性

Thymeleaf属性与html属性作用一致。只不过添加了th前缀,属性的值交由模板引擎处理了,在属性中可以使用变量表达式。
1、th:action,th:href

<form th:action="@{/login}" th:method="post"></form>

2、th:method

<form th:action="/login" th:method="${methodArr}"></form>

3、th:src
用于外部资源引入,常用@{}表达式可结合使用,在springboot项目的静态资源都放到resources的static目录下,项目路径中不需要写上static

<script type="text/javascript" th:src="@{/js/jquery.js}"></script>

4、th:text 、th:value
用于文本的显示,该属性显示的文本在标签体中。如果是文本框,数据会显示在文本框外,如果要显示在文本框内,需要使用th:value

5、th:style
设置样式

<a th:onclick=" 'fun1('+${id}+)'" th:style="'color:red'"></a>

6、th:each
用来遍历后台传来的一个对象集合,它与JSTL中的<c:foreach>类似。此属性既可以循环遍历集合,也可以循环遍历数组及Map
语法:

<div th:each="集合成员变量,循环状态变量:${key}">
	<p th:text="${集合变量}"></p>
</div>

说明:集合成员变量和循环状态变量可以自定义。循环状态变量可以不定义:默认是“集合成员变量Stat”

index:当前迭代对象的index(从0开始计算)
count:当前已迭代对象的个数(从1开始计算)
size:被迭代对象的集合大小
current:当前迭代变量
even/odd:布尔值,当前循环是否是偶数/奇数(从0开始计算)
first:布尔值,当前循环是否是第一个
last:布尔值,当前循环是否是最后一个

示例:

<body>
    <h3>标签属性</h3>
    <p>遍历Array,List</p>
    <div th:each="stu,stuIter:${list}">
        <p th:text="${stu.id}"></p>
        <p th:text="${stu.name}"></p>
        <p th:text="${stu.age}"></p>
    </div>
	<p>遍历Map</p>
    <div th:each="map:${map}">
        <p th:text="${map.key}"></p>
        <span th:text="${map.value.id}"></span>
        <span th:text="${map.value.name}"></span>
        <span th:text="${map.value.age}"></span>
    </div>
</body>

7、条件判断if
语法:th:if=“boolean条件”,条件为真则显示标签体的内容。th:unless是th:if的一个相反操作
示例:

    <div>
        <p th:if="${male == ''}">条件为真时显示数据</p>
        <p th:unless="${female == ''}">条件为假时显示数据</p>
        <p th:if="${cdn}">cdn为空串时为真,为null时为假</p>
    </div>

8、switch、case判断语句

<div th:switch="${sex}">
	<p th:case="m"></p>
	<p th:case="f"></p>
	<p th:case="*">都不匹配,默认值</p>
</div>

9、th:inline
th:inline有三个取值:text、javascript、none
9.1 内联text
可以让Thymeleaf表达式不依赖与html标签,直接使用内敛表达式“[[表达式]]”动态获取数据。(要求在父级标签上加“ th:inline=“text” ”属性)

<div th:inline="text">
	<p>显示姓名是:[[${key}]]</p>
</div><div>
	<p>显示姓名是:[[${key}]]</p>
</div>

9.2、内联 javascript
可以在js中,获取模板中的数据

<button onclick="fun()">单击按钮</button>
<script th:inline="javascript">
	var name=[[${stu.name}]];
	var age-[[${stu.age}]];
	function fun(){
		alert("学生姓名:"+name+"性别:"+age);
	}
</script>

五、字面量

5.1、文本字面量
用单引号 '…'包围的字符串为文本字面量

<p th:text="'城市是'+${city}+'  用户登录'+${isLogin}"></p>

5.2、数字字面量

<p th:if="${age >10}">age>10</p>
<p th:if="5<10">5<10</p>

5.3、boolean字面量

<p th:if="${isLogin == true}">用户已登录</p>

5.4、null字面量

<p th:if="${name == null}">name是null</p>

六、字符串连接

字符串连接:1、使用 ‘…’+‘…’ 2、使用|字符串内容|

<p th:text="'城市是'+${city}+'  用户登录'+${isLogin}"></p>
<p th:text="|城市是${city}  用户登录${isLogin}|"></p>

七、运算符

算数运算:+,-,*,/,%
关系比较:>,<,>=,<=(gt,lt,ge,le)
相等判断:==,!=(eq,ne)
三元运算符: 条件?表达式1:表达式2

八、Thymeleaf基本对象

8.1、#request 表示HttpServletRequest

<p th:text="${#request.getArrtibute('data')}">request作用域</p>

8.2、#session 表示HttpSession

<p th:text="${#session.getArrtibute('data')}">session作用域</p>

8.3、session 表示HttpSession(Map(String,Object)),不能调用对象方法

<p th:text="${session.data}">session作用域</p>

其他内置对象查看官方手册

九、Thymeleaf内置工具类对象

模板引擎提供的一组功能性内置对象,可以在模板中直接使用这些对象提供的方法。
内置功能对象前都需要加#号,一般以s结尾
如:
在这里插入图片描述使用示例:
日期格式化:
在这里插入图片描述官方文档参考:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-b-expression-utility-objects

null处理:

询问对象是否为null,如果为null则不取值
<p th:text="${zoo?.dog?.name}"></p>

十、内容复用

10.1、自定义模板
语法:th:fragment=“模板自定义名称”

head.html:
<div th:fragment="top">
	<p>Thymeleaf的使用</p>
</div>

10.2、引用模板
语法:~{模板文件名 :: 自定义模板名称} 或 模板文件名称 :: 自定义模板名称
插入模板:th:insert
包含模板:th:include
示例:

语法1:<div th:insert="~{ head :: top }">此处有内容会被覆盖掉</div>
插入后:
<div th:insert="~{ head :: top }">
	<div th:fragment="top">
		<p>Thymeleaf的使用</p>
	</div>
</div>

语法2:<div th:include="head :: top">此处有内容会被覆盖掉</div>
包含后:
	<div th:include="head :: top">
		<p>Thymeleaf的使用</p>
	</div>

10.3、整个html文件作为模板
语法:

<div th:include="head :: html">此处有内容会被覆盖掉</div><div th:insert="head">此处有内容会被覆盖掉</div>

10.4、使用其他目录中的模板

<div th:include="common/head :: html">此处有内容会被覆盖掉</div><div th:include="common/head">此处有内容会被覆盖掉</div>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值