Thymeleaf详解
Thymeleaf详解
简单介绍
thymeleaf是一个可以完全替代jsp的模板引擎,thymeleaf 在有网络和无网络的环境下皆可运行:
- 实现前后端分离,它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示;
- 它可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、修改jstl、修改标签的困扰;
- Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能
环境搭建
这里以springboot结合的thymaleaf,jar包引入
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
<commons.io.version>2.5</commons.io.version>
<commons.fileupload.version>1.3.3</commons.fileupload.version>
<jsoup.version>1.11.3</jsoup.version>
<poi.version>3.17</poi.version>
<pagehelper.boot.version>1.2.5</pagehelper.boot.version>
<fastjson.version>1.2.47</fastjson.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring-boot-devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional> <!-- 表示依赖不会传递 -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- SpringBoot 拦截器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- Spring框架基本的核心工具 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- servlet包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!--常用工具类 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!-- JSON工具类 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!-- 阿里JSON解析器 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!-- yml解析器 -->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork> <!-- 如果没有该配置,devtools不会生效 -->
</configuration>
</plugin>
</plugins>
</build>
application.yml配置文件,yml文件要有yml解析器;
项目配置的视图默认是放在资源文件的templates目录下;
而视图解析器默认前缀:/templates/,后缀:.html。
# 开发环境配置
server:
# 服务端口
port: 8080
servlet:
# 项目contextPath
context-path: /
tomcat:
# tomcat的URI编码
uri-encoding: UTF-8
# tomcat最大线程数,默认为200
max-threads: 800
# Tomcat启动初始化的线程数,默认值25
min-spare-threads: 30
# Spring配置
spring:
# 模板引擎
thymeleaf:
mode: HTML
encoding: utf-8
# 禁用缓存
cache: false
# 资源信息
messages:
# 国际化资源文件路径
basename: i18n/messages
jackson:
time-zone: GMT+8
date-format: yyyy-MM-dd HH:mm:ss
# 服务模块
devtools:
restart:
# 热部署开关
enabled: true
控制器代码,随便写了一些,用于向前端返回数据
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/showInfo")
public String showInfo(Integer id, Model model){
//基本数据返回
model.addAttribute("msg","Hello Thymaleaf!");
model.addAttribute("date",new Date());
model.addAttribute("sex",0);
List list = new ArrayList();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
list.add("f");
model.addAttribute("list",list);
ServletUtils.getRequest().setAttribute("request","request");
ServletUtils.getSession().setAttribute("session","session");
ServletUtils.getSession().getServletContext().setAttribute("application","application");
System.out.println(id);
return "user";
}
}
语法详解
首先,创建HTML页面,在html页面中定义xmlns属性
<html lang="en" xmlns:th="http://www.thymeleaf.org">
th:text
最简单的一种,替换标签中的文本内容
<span th:text="Hello"></span>
<hr/>
<span th:text="${msg}">aaaaaaaaaaa</span>
th:value
与th:text类似,它是用来替换表单中的值。
<p>
<input type="text" th:value="${msg}"/>
</p>
th:href(th:src)
表达式以@开头:@{ 访问路径 }
<!-- thymeleaf URL表达式 -->
<div>
<a th:href="@{/user/showInfo}">link</a>
</div>
条件判断
- th:if
<p>
<span th:if="${sex==1}">
男
</span>
<span th:if="${sex==0}">
女
</span>
</p>
- th:switch
<p>
<div th:switch="${sex}">
<span th:case="1">男</span>
<span th:case="0">女</span>
</div>
</p>
th:each
迭代遍历,a代表每个集合中便利到的对象,s代表对象的状态,:之后是要遍历的集合。
<div>
<div th:each="a,s : ${list}">
<span th:text="${a}"></span>,
<span th:text="${#strings.concat('index--',s.index)}"></span>,
<span th:text="${#strings.concat('count--',s.count)}"></span>,
<span th:text="${#strings.concat('first--',s.first)}"></span>,
<span th:text="${#strings.concat('last--',s.last)}"></span>,
<span th:text="${#strings.concat('current--',s.current)}"></span>,
<span th:text="${#strings.concat('odd--',s.odd)}"></span>,
<span th:text="${#strings.concat('size--',s.size)}"></span>,
</div>
</div>
Thymeleaf内置对象
Thymeleaf内置对象的语法${# }内部必须以 # 开头
strings
- 判断字符串是否为空,strings.isEmpty()
<p>
<span th:text="${#strings.isEmpty(msg)}"></span>
</p>
- 判断是否包含某个字符串,strings.contains(msg,‘Th’)
<p>
<span th:text="${#strings.contains(msg,'Th')}"></span>
</p>
- 判断是否字符串是否以指定字符串开头/结尾的 区分大小写
<p>
<span th:text="${#strings.startsWith(msg,'Hello')}"></span>
<span th:text="${#strings.endsWith(msg,'Hello')}"></span>
</p>
- 截取字符串,substring()
<p>
<span th:text="${#strings.substring(msg,1)}"></span>
</p>
<p>
<span th:text="${#strings.substring(msg,6,9)}"></span>
</p>
方法有很多,大家可以在网上查。
dates
- 格式化日期
<p>
<span th:text="${#dates.format(date,'yyyy-MM-dd HH:mm:ss')}"></span>
</p>
- 获取年月日
<p>
<span th:text="${#dates.year(date)}"></span>
</p>
<p>
<span th:text="${#dates.month(date)}"></span>
</p>
<p>
<span th:text="${#dates.day(date)}"></span>
</p>
Web作用域对象
- request
<span th:text="${#httpServletRequest.getAttribute('request')}"></span><br/>
- session
<span th:text="${#session.getAttribute('session')}"></span><br/>
- application
<span th:text="${#servletContext.getAttribute('application')}"></span>
Thymeleaf 在 javascript 中的使用
我们可以在js代码内部直接获取返回的值
<script th:inline="javascript">
var request = [[${#servletContext.getAttribute('application')}]];
alert(request);
</script>
方法还有很多,大家可以在网上查找。
第一次写博客,以前都是记录在笔记本上,现在想跟大家分享一些下,也给自己做一些学习记录,如有什么地方不对,还请大家批评指出,谢谢。