thymeleaf
1.什么是thymeleaf
Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。
https://www.imooc.com/article/20304
2.thymeleaf的特点
- Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
- Thymeleaf 开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
- Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
3.thymeleaf的第一个应用程序
1.创建spring boot项目
2.所需依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3.相关配置
server.port=9999
# 这个是配置模板路径的,默认就是templates,可不用配置
spring.thymeleaf.prefix=classpath:/templates/
# 可以不配置,默认.html
spring.thymeleaf.suffix=.html
4.入口类
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
5.controller
@Controller
public class TestController {
@RequestMapping("test")
public String test(Model model){
model.addAttribute("name","张三");
return "index";
}
}
6.引入thymeleaf的模板
需要添加<html lang="en" xmlns:th="http://www.thymeleaf.org">
标明 th
标签,添加css需要填写href
和th:href
属性,href属性是为了能够在不启动服务的情况下预览html,也是默认值,th:href是为了使用时候替代href。
7.thymeleaf热部署相关配置
<!-- 开启热部署(必须false) -->
spring.thymeleaf.cache=false
后端代码热部署
<!-- 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<version>2.0.4.RELEASE</version>
<!-- 启用 -->
<optional>true</optional>
</dependency>
7.1 手动编译
页面发生更改,ctrl+f9 手动编译
7.2 自动编译
ctrl+alt+s
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jrMREzrU-1583481095216)(assets/Snipaste_2019-06-24_13-11-55.png)]
ctrl+alt+shift+/
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FAPQwQ8g-1583481095218)(assets/Snipaste_2019-06-24_13-14-00.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RbhUxxu7-1583481095218)(assets/a.png)]
4.引入静态资源的注意事项
thymeleaf默认的存放目录是resources/templates
,css和js文件默认的存放路径是resources/static
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ic9FlLen-1583481095218)(assets/2019-06-24_151954.png)]
<script th:src="@{/jquery-2.2.1.min.js}"></script>
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WnG2orUt-1583481095219)(assets/2019-06-24_152142.png)]
<script th:src="@{/js/jquery-2.2.1.min.js}"></script>
5.thymeleaf标准表达式语法
分为四类:
- 1.变量表达式
- 2.选择或星号表达式
- 3.文字国际化表达式
- 4.URL 表达式
4.1变量表达式
变量表达式即 OGNL 表达式或 Spring EL 表达式(在 Spring 术语中也叫 model attributes)
它们将以HTML标签的一个属性来表示:
<!-- 展示基本类型数据 -->
<标签 th:text="${变量名}">
例如:
<span th:text="${username}">
注意:
1). th:text 用来将内容输出到所在标签的body中
2). 可以用th:utext 用来显示“unescaped ” 的html内容。–>可以解析html标签
<!-- 展示对象类型数据 -->
<标签 th:text="${对象变量名.对象中属性}"></标签>
例如:
<span th:text="${user.username}">
<span th:text="${session.user.username}">
<!-- 展示集合类型数据 -->
<标签 th:each="自定义变量名 : ${集合变量名}