1. Thymeleaf基本使用
1.1 springboot集成thymeleaf
Thymeleaf是一个用于web和独立环境的现代服务器端Java模板引擎。
Thymeleaf是用来替换传统的jsp,做项目的展示的,SpringBoot里面并不推荐使用jsp了,推荐使用Thymeleaf,Thymeleaf可以运行在有网络的环境里,同时它也可以用在无网络的外部环境里,而有一些模板必须需要服务器才能运行。美工在开发的时候只能改html,我们在开发的时候得把html变成jsp,Thymeleaf可以运行在服务器里面,也可以本地运行,它既可以让美工在浏览器查看页面的静态效果,也可以让开发人员在服务器端看动态数据渲染之后的效果。
Thymeleaf是一个java的模板引擎,是用来显示数据的,Thymeleaf有一个要求,不能直接通过请求访问到Thymeleaf,Thymeleaf在用的时候,要访问Thymeleaf,必须得经过controller,由controller跳转到Thymeleaf,它才能得到一个正确的显示。
那么如何集成thymeleaf模板呢
用到的包结构:
- 引入依赖
<!--使用thymelaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- 编写配置
把Thymeleaf相关的模板都放到项目中的templates这个目录,css、js等静态资源放在static这个目录里面
需要在配置文件里告诉它模板在resources/templates里面,
指定thymeleaf模板目录和指定模板的后缀是默认的,不在配置文件里写也是可以的
spring:
thymeleaf:
prefix: classpath:/templates/ # 指定thymeleaf模板前缀目录
suffix: .html # 指定模板的后缀
cache: false # 是否开启thymeleaf缓存,默认为true是开启的,在开发过程中建议 # 关了
注:不使用缓存时我们还得设置一下,使themeleaf模板的修改随时生效
- 开发html页面并导入thymeleaf的头表示这是一个thymeleaf模板
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>springboot 之 thymeleaf 使用</title>
</head>
<body>
<h1>thymeleaf 入门案例</h1>
</body>
</html>
开发的thymeleaf需要放在templates包里
使用时必须在页面中加入thymeleaf命名空间(导入thymeleaf的头)
将
<html lang="en">
修改为
<html lang="en" xmlns:th="http://www.thymeleaf.org">
ns表示namespace命名空间,冒号后面的th表示当前命名空间的名字,名字可以随便写,不过后面用的时候都得使用这个名字去使用,一般都写为th
- 开发controller
HelloController
package com.baizhi.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("hello")
public class HelloController {
@RequestMapping("hello")
public String hello(){
System.out.println("hello ok...");
return "index";
}
}
如果直接在地址栏里访问thymeleaf的话thymeleaf语法是不生效的,所以我们需要先访问controller,由controller跳转到thymeleaf这样的话thymeleaf语法才生效,跳转时的语法和原来是一样的。
forward跳转:
return “index”;
当访问hello/hello的时候,它会返回一个视图,叫index,同时会经过视图解析器,在classpath:/templates/找一个index.html
- 测试访问
注:如果直接访问项目名 http://localhost:8989/springboot_day7/ 不访问controller中的方法那么默认访问项目中的index.html
1.2 Thymeleaf基本语法
在使用html作为thymeleaf模板时,必须将
<html lang="en">
修改为
<html lang="en" xmlns:th="http://www.thymeleaf.org">
传递数据
//forward跳转: request、model 作用域传递数据
//redirect跳转: session作用域传递数据
//传递单个(基本类型)数据 String Integer
//传递对象类型数据
//传递集合类型数据
//如何在页面有条件展示数据 判断
获取request作用域中的数据
获取单个(基本类型)数据
获取接以文本形式输出
直接以文本形式输出
在controller的方法中传递数据
String name = "小陈";
Integer age = 23;
request.setAttribute("name", name);
request.setAttribute("age", age);
在themeleaf模板里获取数据
<h4>获取单个数据:<span th:text= "${name}"></span></h4>
<h4>获取单个数据:<span th:text= "${age}"></span></h4>
获取的是一段html标签
controller中传递数据:
String content = "<a href='http://www.baidu.com'>百度一下<a/>";
request.setAttribute("content", content);
thymeleaf模板中获取数据:
直接以原样(html标签形式)输出
th:text="${content}"
<h4>获取单个数据:<span th:text= "${content}"></span></h4>
如果想要先解析获取到数据之后想要先解析,而不是直接以文本形式输出
th:utext="${content}"
<h4>获取单个数据:<span th:utext= "${content}"></span></h4>
补充
如果想让作用域中的数据赋值给表单元素,想让标签的value是controller方法作用域获取的
th这个命名空间除了可以写th:text以外,它还可以加在html标签的任意属性上
<input type="text" name="username" th:value="${name}">
另外:span标签可以写成自闭和标签,也可以写成围堵标签
# 总结
- 1.使用 th:text="${属性名}" 获取对应数据,获取数据时会将对应标签中数据清空,因此最好是空标签
- 2.使用 th:utext="${属性名}" 获取对应的数据,可以将数据中html先解析在渲染到页面
- 3.使用 th:value="${属性名}" 获取数据直接作为表单元素value属性
获取对象类型数据
controller的方法中传递数据:
User user = new User(21, "小张", 2300.23, new Date());
request.setAttribute("user", user);
themeleaf模板中获取数据:
<h4>
获取对象类型数据:
id:<span th:text="${user.id}"/>
name:<span th:text="${user.name}"/>
salary:<span th:text="${user.salary}"/>
birthday:<span th:text="${user.birthday}"/>
</h4>
日期格式化
<!--格式化日期: ${#dates.format(格式化值, '格式')}-->
birthday:<span th:text="${#dates.format(user.birthday, 'yyyy-MM-dd')}"/>
集合类型数据
controller的方法中传递数据:
// 传递集合类型数据
List<User> users = Arrays.asList(new User(22, "小黄", 232.2, new Date()),
new User(23, "小王", 232.2, new Date()),
new User(24, "win7", 232.2, new Date()));
request.setAttribute("users", users);
themeleaf模板中获取数据:遍历集合
只有一个变量:每次遍历到的元素
<!--遍历数据 th:each="变量名(当前遍历出的元素):集合" 遍历
集合中每次取出来的赋值给变量
-->
<ul>
<li th:each="user:${users}">
id: <span th:text="${user.id}"/>
name: <span th:text="${user.name}"/>
salary: <span th:text="${user.salary}"/>
birthday: <span th:text="${user.birthday}"/>
<!--生日格式化-->
birthday格式化: <span th:text="${#dates.format(user.birthday, 'yyyy年MM月dd日')}"/>
</li>
</ul>
两个变量:每次遍历到的元素,状态
<!--遍历数据 th:each="变量名(当前遍历出的元素),state(状态):集合" 遍历
集合中每次取出来的赋值给变量
-->
<ul th:each="user,userStat:${users}">
<li><span th:text="${userStat.count}"/>-<span th:text="${user.id}"/></li> 获取遍历次数 count 从1开始 index 从0开始
<li><span th:text="${userStat.odd}"/>-<span th:text="${user.name}"/></li> 获取当前遍历是否是奇数行
<li><span th:text="${userStat.even}"/>-<span th:text="${user.age}"/></li> 获取当前遍历是否是偶数行
<li><span th:text="${userStat.size}"/>-<span th:text="${user.bir}"/></li> 获取当前集合的总条数
</ul>
有条件的展示数据
controller方法中将数据放入request作用域
Integer age = 23;
request.setAttribute("age", age);
themeleaf模板中获取数据:
<h4>有条件的展示数据:</h4>
<!-- th:if="${age>=23}" 作用: 有条件的展示数据-->
<div style="width: 100px;height: 100px;background: rebeccapurple;" th:if="${age>=23}">
我是rebeccapurple
</div>
<div style="width: 100px;height: 100px;background: green;" th:if="${age<23}">
我是green
</div>
# 运算符
gt:great than(大于)>
ge:great equal(大于等于)>=
eq:equal(等于)==
lt:less than(小于)<
le:less equal(小于等于)<=
ne:not equal(不等于)!=
而age=23,所以应该输出 “我是rebeccapurple”
获取session作用域中的数据
获取session中数据使用session.key
controller的方法中将数据放入session作用域:
// 向session作用域存储数据
session.setAttribute("username", "小二黑");
themeleaf中获取数据:
<h4>获取session作用域中数据: <span th:text="${session.username}"></span></h4>
获取application作用域中的数据
获取application中的数据:application.key
获取application作用域中的数据需要在数据名字前面加上 application.
测试
资源类User
public class User {
private Integer id;
private String name;
private Double salary;
private Date birthday;
// 提供有参、无参构造方法,get、set方法
// 以免影响阅读,这里没有粘,但其实是有的
}
DemoController
package com.baizhi.controller;
import com.baizhi.eneity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@Controller
@RequestMapping("demo")
public class DemoController {
//forward跳转: request、model 作用域传递数据
//redirect跳转: session作用域传递数据
//传递单个(基本类型)数据 String Integer
//传递对象类型数据
//传递集合类型数据
//如何在页面有条件展示数据 判断
@RequestMapping("demo")
public String demo(HttpServletRequest request, HttpSession session){
System.out.println("demo ok");
// 传递单个(基本)类型数据
String name = "小陈";
Integer age = 23;
String content = "<a href='http://www.baidu.com'>百度一下<a/>";
request.setAttribute("name", name);
request.setAttribute("age", age);
request.setAttribute("content", content);
// 传递对象类型数据
User user = new User(21, "小张", 2300.23, new Date());
request.setAttribute("user", user);
// 传递集合类型数据
List<User> users = Arrays.asList(new User(22, "小黄", 232.2, new Date()),
new User(23, "小王", 232.2, new Date()),
new User(24, "win7", 232.2, new Date()));
request.setAttribute("users", users);
// 向session作用域存储数据
session.setAttribute("username", "小二黑");
return "demo";
}
}
demo.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用来测试thymeleaf语法</title>
</head>
<body>
<h1>thymeleaf语法基本使用</h1>
<!--<span th:text= "${name}"></span>-->
<!--thymeleaf语法可以作用于任何标签-->
<!--th:text= "${数据名}" 获取数据,作用:直接将获取的数据以文本的形式渲染到页面上-->
<!--配合命名空间取值 th代表头(命名空间的名字),text代表文本的意思,往span标签里展示文本-->
<h4>获取单个数据:<span th:text= "${name}"></span></h4>
<h4>获取单个数据:<span th:text= "${age}"></span></h4>
<h4>获取单个数据:<span th:utext= "${content}"></span></h4>
<input type="text" name="username" th:value="${name}">
<!--格式化日期: ${#dates.format(格式化值, '格式')}-->
<h4>
获取对象类型数据:
id:<span th:text="${user.id}"/>
name:<span th:text="${user.name}"/>
salary:<span th:text="${user.salary}"/>
<!--格式化中间的横杠可以随便写成其他的,比如年、月、日-->
birthday:<span th:text="${#dates.format(user.birthday, 'yyyy-MM-dd')}"/>
</h4>
<h4>获取集合类型数据:</h4>
<!--遍历数据 th:each="变量名(当前遍历出的元素),变量(遍历的状态):集合" 遍历
集合中每次取出来的赋值给变量
-->
<ul>
<li th:each="user,state:${users}">
state count: <span th:text="${state.count}"/> <!--获取当前遍历的次数-->
state odd: <span th:text="${state.odd}"/> <!--当前行是否是奇数行-->
state even: <span th:text="${state.even}"/> <!--当前行是否是偶数行-->
state size: <span th:text="${state.size}"/> <!--获取集合中元素数量-->
id: <span th:text="${user.id}"/>
name: <span th:text="${user.name}"/>
salary: <span th:text="${user.salary}"/>
birthday: <span th:text="${user.birthday}"/>
<!--生日格式化-->
birthday格式化: <span th:text="${#dates.format(user.birthday, 'yyyy年MM月dd日')}"/>
</li>
</ul>
<h4>有条件的展示数据:</h4>
<!-- th:if="${age>=23}" 作用: 有条件的展示数据-->
<div style="width: 100px;height: 100px;background: rebeccapurple;" th:if="${age>=23}">
我是rebeccapurple
</div>
<div style="width: 100px;height: 100px;background: green;" th:if="${age<23}">
我是green
</div>
<h4>获取session作用域中数据: <span th:text="${session.username}"></span></h4>
</body>
</html>
效果
1.3 Themeleaf中引入静态资源
静态资源默认放在static包里面
默认静态资源从static里面找,所以找静态资源的时候直接 项目名/静态资源名 就ok了,
-
themeleaf模板中引入静态资源
<!-- th:href="@{/}" @{/}:获取应用名称 --> <!--themeleaf中引入css--> <link rel="stylesheet" th:href="@{/demo.css}"> <!--themeleaf中引入js--> <script th:src="@{/demo.js}"></script>
注意: @{/}代表通过thymeleaf语法动态获取应用名
-
在js代码中获取项目名
<script>
const ctx = '[[@{/}]]';
</script>
注意:[[书写thymeleaf语法]],这里[[]]是thymeleaf内嵌表达式