1、thymeleaf是java服务端的模板引擎,在springBoot中推荐使用thymeleaf模板引擎。它有如下特点:
1)、可以动态的显示网页内容。
2)、使用方便,功能强大。
3)、语法格式类似于html。
2、引入thymeleaf依赖
在pom.xml文件中引入thymeleaf的maven依赖
org.springframework.boot
spring-boot-starter-thymeleaf
2、切换thymeleaf版本的方法
1)、在pom.xml文件中加入以下代码,注意二者之间的适配关系。
3.0.11.RELEASE
2.3.0
2)、在 https://github.com/thymeleaf/thymeleaf 搜索 thymeleaf ,可以找到相应版本。
3)、在 https://github.com/search?q=thymeleaf-layout-dialect 找到布局相应的版本。
3、thymeleaf使用
1)、thymeleaf会自动渲染 classpath:/templates/ 的html页面。
2)、在html页面导入thymeleaf。
4)、在@controller注解的类下,加入以下代码。
5)、访问 http://localhost:8080/success
4、thymeleaf语法
1)、th:text="${}": 改变当前元素里面的文本内容。
2)、html属性都可以替换写成th:形式。
5、thymeleaf属性优先级。
6)、thymeleaf表达式语法
Simple expressions:
1)、获取变量值
2)、获取对象的属性和调用方法
Variable Expressions: ${...}
1)、选择表达式
Name: Sebastian.
Surname: Pepper.
Nationality: Saturn
Selection Variable Expressions: *{...}
获取国际化内容
Message Expressions: #{...}
定义URL链接
view
Link URL Expressions: @{...}
片段引用表达式
...
Fragment Expressions: ~{...}
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: _
7)、实例代码
controller类
@RequestMapping("/success")
public String success(Map map) {
map.put("hello", "你好
");
map.put("users", Arrays.asList("zhangsan","lisi","wangwu"));
return "success";
}
HTML
Title
hello world
[[${user}]]