1、引入thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
修改thymeleaf的版本(maven依赖的版本参照此处修改),在<properties>标签中指定版本即可:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.2.2.RELEASE</thymeleaf-layout-dialect.version>
</properties>
2、Thymeleaf的自动配置
在SpringBoot的autoconfigure下有一个thymeleaf模块:
使用的时候可以根据ThymeleafProperties中的属性进行配置:
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
private boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
private String prefix = "classpath:/templates/";
private String suffix = ".html";
...
}
可以看到默认的模板路径为:"classpath:/templates/",模板的后缀名为:html
例如:
Controller:
@Controller
public class TestController {
@RequestMapping("/hello")
public String hello() {
return "success";
}
}
模板位置:
由此看出我们只需要将html页面放在指定的路径下,该html在被请求之后就会由浏览器渲染
3、Thymeleaf的语法
①使用Thymeleaf前,最好先导入其名称空间:xmlns:th,不导入会没有提示,但不影响使用
<html lang="en" xmlns:th="http://www.thymeleaf.org">
②使用的demo:
controller:map中放入一个键值对传入到前端
@Controller
public class TestController {
@RequestMapping("/hello")
public String hello(Map<String,Object> map) {
map.put("name","哼哼");
return "success";
}
}
html:前端使用th:text接收并展示
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${name}">姓名</div>
</body>
</html>
在展示的时候th:text中的值会替换掉div的文本内容,thymeleaf还有个优点,就是使用th符号的html页面在纯静态网站中也可以展示为前端的效果,而不是像jsp那样无法运行
③语法规则
1)、th:任意html属性:来替换原生属性的值,这样就可以动态的为html元素的所有属性赋值
<div id="div01" th:id="${name}" th:text="${name}">姓名</div>
以下为thymeleaf的th:属性和jsp中的c标签的比较:
2)、五种表达式
a、ognl表达式${...}
a1、获取对象的属性、调用方法
a2、使用内置的基本对象:
#ctx: the context object.
#vars: the context variables.
#locale: the context locale.
#request: (only in Web Contexts) the HttpServletRequest object.
#response: (only in Web Contexts) the HttpServletResponse object.
#session: (only in Web Contexts) the HttpSession object.
#servletContext: (only in Web Contexts) the ServletContext object.
${session.foo}
a3、内置的工具对象:
#execInfo : information about the template being processed.
#messages : methods for obtaining externalized messages inside variables expressions, in the
same way as they would be obtained using #{…} syntax.
#uris : methods for escaping parts of URLs/URIs
#conversions : methods for executing the configured conversion service (if any).
#dates : methods for java.util.Date objects: formatting, component extraction, etc.
#calendars : analogous to #dates , but for java.util.Calendar objects.
#numbers : methods for formatting numeric objects.
#strings : methods for String objects: contains, startsWith, prepending/appending, etc.
#objects : methods for objects in general.
#bools : methods for boolean evaluation.
#arrays : methods for arrays.
#lists : methods for lists.
#sets : methods for sets.
#maps : methods for maps.
#aggregates : methods for creating aggregates on arrays or collections.
#ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
b、选择表达式*{...},和${...}在功能上是一样,但是可以补充th:object
<div th:object="${session.user}">
<p>Name: <span th:text="*{firstName}">Sebastian</span></p>
<p>Surname: <span th:text="*{lastName}">Pepper</span></p>
<p>Nationality: <span th:text="*{nationality}">Saturn</span></p>
</div>
此处的*表示th:object中的session.user,相当于${session.user.firstName}...
c、获取国际化内容#{...}
d、定义URL@{...}
@{/order/process(execId=${execId},execType='FAST')}
/order/process表示当前应用下的/order/process请求,()中的内容表示请求参数键值对
e、片段引用表达式~{...}
<div th:insert="~{commons :: main}">...</div>
3)、这些表达式中支持的操作
Literals(字面量)
Text literals: 'one text' , 'Another one!' ,…
Number literals: 0 , 34 , 3.0 , 12.3 ,…
Boolean literals: true , false
Null literal: null
Literal tokens: one , sometext , main ,…
Text operations:(文本操作)
String concatenation: +
Literal substitutions: |The name is ${name}|
Arithmetic operations:(数学运算)
Binary operators: + , ‐ , * , / , %
Minus sign (unary operator): ‐
Boolean operations:(布尔运算)
Binary operators: and , or
Boolean negation (unary operator): ! , not
Comparisons and equality:(比较运算)
Comparators: > , < , >= , <= ( gt , lt , ge , le )
Equality operators: == , != ( eq , ne )
Conditional operators:条件运算(三元运算符)
If‐then: (if) ? (then)
If‐then‐else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)
Special tokens:
No‐Operation: _(什么都不做,比如:(if) ? (then) :_,条件不满足则什么都不做)
④demo:
controller:
@Controller
public class TestController {
@RequestMapping("/hello")
public String hello(Map<String,Object> map) {
map.put("name","哼哼");
map.put("content","<h1>大标题</h1>");
map.put("friends", Arrays.asList("张三","李四","王五"));
return "success";
}
}
html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="div01" th:id="${name}" th:text="${name}">姓名</div>
<hr/>
<div th:text="${content}"></div>
<div th:utext="${content}"></div>
<hr/>
<h4 th:text="${friend}" th:each="friend : ${friends}"></h4>
<hr/>
<h4>
<span th:each="friend : ${friends}">
[[${friend}]]
</span>
</h4>
</body>
</html>
th:text:会将html标签等转义为字符串,也就是说会按照原有字符串输出
th:utext:不会将html标签转义为字符串,此部分会由浏览器解析为标签
th:each:放在哪个标签上就会生成多个该标签,遍历的结果可以使用一个变量来接收,该变量可用于th:text等,变量的显示也可以使用行内写法[[]]或者[()],前者相当于th:text,后者相当于th:utext
效果: