一、引入Thymeleaf
1.1、什么是模板引擎
- 概念 :模板引擎是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的文档;就是将模板文件和数据通过模板引擎生成一个HTML代码
- 常用的模板引擎:JSP、Velocity、Freemarker、Thymeleaf;springboot推荐的是Thymeleaf
1.2、引入Thymeleaf
1、maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、thymeleaf版本问题
- 我们可以看到springboot默认导入的是这个thymeleaf版本:2.1.4
- 点击查看spring-boot-starter-thymeleaf ;我们发现它已经集成了最新的thymeleaf版本
- 以上是spring-boot-dependencies中关于thymeleaf的所有依赖配置。
1.3、springboot官网版本介绍
-
GA:General Availability,正式发布的版本,官方推荐使用此版本。在国外都是用GA来说明release版本的。
-
PRE: 预览版,内部测试版. 主要是给开发人员和测试人员测试和找BUG用的,不建议使用;
-
SNAPSHOT: 快照版,可以稳定使用,且仍在继续改进版本。
1.4、使用Thymeleaf
1、Thymeleaf的配置类
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
/**
* Whether to check that the template exists before rendering it.
*/
private boolean checkTemplate = true;
/**
* Whether to check that the templates location exists.
*/
private boolean checkTemplateLocation = true;
- 只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染
2、导入thymeleaf的名称空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
3、测试
-
在templates文件夹下面创建一个success.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>springboot 测试页面访问成功</h1> </body> </html>
-
控制器Controller;注意:必须是controller不能是restcontroller
//注意:必须是controller不能是restcontroller @Controller @RequestMapping("/test") public class TestController { @GetMapping("/hello") public String hello(){ return "hello word"; } @GetMapping("/success") public String success(){ return "success"; } }
-
测试结果:http://localhost:8080/test/success
二、Thymeleaf语法
2.1、语法结构图
2.2、th属性
1、常用th属性解读:其中th属性执行的优先级order从1~8,数字越低优先级越高
-
th:text :设置当前元素的文本内容,相同功能的还有th:utext,两者的区别在于前者不会转义html标签,后者会。优先级不高:order=7
-
th:value:设置当前元素的value值,类似修改指定属性的还有th:src,th:href(CSS使用th:href,js使用使用th:src)。优先级不高:order=6
-
th:each:遍历循环元素,和th:text或th:value一起使用。注意该属性修饰的标签位置,详细往后看。优先级很高:order=2
-
th:if:条件判断,类似的还有th:unless,th:switch,th:case。优先级较高:order=3
-
th:insert:代码块引入,类似的还有th:replace,th:include,三者的区别较大,若使用不恰当会破坏html结构,常用于公共代码块提取的场景。优先级最高:order=1
-
th:fragment:定义代码块,方便被th:insert引用。优先级最低:order=8
-
th:object:声明变量,一般和*{}一起配合使用,达到偷懒的效果。优先级一般:order=4
-
th:attr:修改任意属性,实际开发中用的较少,因为有丰富的其他th属性帮忙,类似的还有th:attrappend,th:attrprepend。优先级一般:order=5
2、使用注意点
-
若要使用Thymeleaf语法,首先要声明名称空间:命名空间详情请看1.4节
-
设置文本内容 th:text,设置input的值 th:value,循环输出 th:each,条件判断 th:if,插入代码块 th:insert,定义代码块 th:fragment,声明变量 th:object
-
th:each 的用法需要格外注意,打个比方:如果你要循环一个div中的p标签,则th:each属性必须放在p标签上。若你将th:each属性放在div上,则循环的是将整个div。
-
变量表达式中提供了很多的内置方法,该内置方法是用**#开头**,请不要与**#{}消息表达式**弄混。
-
th:insert,th:replace,th:include 三种插入代码块的效果相似,但区别很大。
3、th:insert,th:replace,th:include的区别
-
th:insert :保留自己的主标签,保留th:fragment的主标签。
-
th:replace :不要自己的主标签,保留th:fragment的主标签。
-
th:include :保留自己的主标签,不要th:fragment的主标签。(官方3.0后不推荐)
-
举例:
需要替换的片段内容: <footer th:fragment="copy"> <script type="text/javascript" th:src="@{/plugins/jquery/jquery-3.0.2.js}"></script> </footer> 导入片段: <div th:insert="footer :: copy"></div> <div th:replace="footer :: copy"></div> <div th:include="footer :: copy"></div> 结果为: <div> <footer> <script type="text/javascript" th:src="@{/plugins/jquery/jquery-3.0.2.js}"></script> </footer> </div> <footer> <script type="text/javascript" th:src="@{/plugins/jquery/jquery-3.0.2.js}"></script> </footer> <div> <script type="text/javascript" th:src="@{/plugins/jquery/jquery-3.0.2.js}"></script> </div>
2.3、表达式
1、常用表达式
-
${…} : 变量表达式,Variable Expressions
-
@{…}: 链接表达式,Link URL Expressions
-
#{…} :消息表达式,Message Expressions
-
~{…} :代码块表达式,Fragment Expressions
-
*{…}: 选择变量表达式,Selection Variable Expressions
2、~{…}代码块表达式
- 主要支持两种语法结构:
1、推荐:~{templatename::fragmentname}
2、支持:~{templatename::#id} - templatename:模版名,Thymeleaf会根据模版名解析完整路径:/resources/templates/templatename.html,要注意文件的路径。
- fragmentname:片段名,Thymeleaf通过th:fragment声明定义代码块,如2.2中的第三节引入模板
<div th:insert="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: copy"></div>
- id:HTML的id选择器,使用时要在前面加上#号,不支持class选择器。
- 使用:代码块表达式需要配合th属性(th:insert,th:replace,th:include)一起使用
3、#{…} 消息表达式
- 消息表达式一般用于国际化的场景。结构:th:text="#{msg}" 。会在后续的实战章节介绍
4、@{…} 链接表达式
-
好处:不管是静态资源的引用,form表单的请求,凡是链接都可以用 @{…} 。这样可以动态获取项目路径,即便项目名变了,依然可以正常访问
-
链接表达式结构:
1、无参:@{/xxx}2、有参:@{/xxx(k1=v1,k2=v2)} 对应url结构: xxx?k1=v1&k2=v2
3、引入本地资源:@{/项目本地的资源路径}
4、引入外部资源:@{/webjars/资源在jar包中的路径}
-
代码示例:
<link th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet"> <link th:href="@{/main/css/itdragon.css}" rel="stylesheet"> <form class="form-login" th:action="@{/user/login}" th:method="post" > <a class="btn btn-sm" th:href="@{/login.html(l='zh_CN')}">中文</a> <a class="btn btn-sm" th:href="@{/login.html(l='en_US')}">English</a>
4、${…}变量表达式;重要
- 变量表达式功能:
1、可以获取对象的属性和方法
2、可以使用ctx,vars,locale,request,response,session,servletContext内置对象
3、可以使用dates,numbers,strings,objects,arrays,lists,sets,maps等内置方法(重点介绍) - 常用的内置对象:
1、ctx :上下文对象。
2、vars :上下文变量。
3、locale:上下文的语言环境。
4、request:(仅在web上下文)的 HttpServletRequest 对象。
5、response:(仅在web上下文)的 HttpServletResponse 对象。
6、session:(仅在web上下文)的 HttpSession 对象。
7、servletContext:(仅在web上下文)的 ServletContext 对象 - 常用的内置方法:
1、strings:字符串格式化方法,常用的Java方法它都有。比如:equals,equalsIgnoreCase,length,trim,toUpperCase,toLowerCase,indexOf,substring,replace,startsWith,endsWith,contains,containsIgnoreCase等
2、numbers:数值格式化方法,常用的方法有:formatDecimal等
3、bools:布尔方法,常用的方法有:isTrue,isFalse等
4、arrays:数组方法,常用的方法有:toArray,length,isEmpty,contains,containsAll等
5、lists,sets:集合方法,常用的方法有:toList,size,isEmpty,contains,containsAll,sort等
6、maps:对象方法,常用的方法有:size,isEmpty,containsKey,containsValue等
7、dates:日期方法,常用的方法有:format,year,month,hour,createNow等 - 具体使用将在实战部分应用讲解
2.4、springboot中的应用
1、引入Thymeleaf依赖
<dependency> <!--引入模版引擎thymeleaf-->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、提取公共页面,提高代码的重用性,统一页面风格
<head th:fragment="common-head">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="initial-scale=1.0, width=device-width, user-scalable=no" />
<title>test</title>
<link type="image/x-icon" href="images/favicon.ico" rel="shortcut icon">
<link th:href="@{/sb-admin-1.0.4/css/bootstrap.min.css}" rel="stylesheet">
<link th:href="@{/sb-admin-1.0.4/css/sb-admin.css}" rel="stylesheet">
<link th:href="@{/sb-admin-1.0.4/css/plugins/morris.css}" rel="stylesheet">
<link th:href="@{/sb-admin-1.0.4/font-awesome/css/font-awesome.min.css}" rel="stylesheet">
<script th:src="@{/sb-admin-1.0.4/js/jquery.js}"></script>
<script th:src="@{/sb-admin-1.0.4/js/bootstrap.min.js}"></script>
<script th:src="@{/sb-admin-1.0.4/js/plugins/morris/raphael.min.js}"></script>
<script th:src="@{/sb-admin-1.0.4/js/plugins/morris/morris.min.js}"></script>
<script th:src="@{/sb-admin-1.0.4/js/plugins/morris/morris-data.js}"></script>
</head>
3、页面显示和国际化功能
第一步:准备好国际化文件,至少三分(系统默认,中文,英文)
第二步:在Spring Boot全局配置文件中,指定国际化文件路径,
第三步:自定义Locale Resolver
第四步:在页面上使用消息表达式输出国际化内容
注意: 具体的Thymeleaf实战应用请查看后续的web开发实战章节