如果开发Web应用前后端不分离,Thymeleaf就会显得十分重要,当然前后端分离的话Thymeleaf也有其用武之地。
jsp支持非常强大的功能,包括能写Java代码,但是SpringBoot项目首先 是以jar的方式,不是war,第二,如果用的是嵌入式的Tomcat,他现在默认是不支持jsp 的。
SpringBoot推荐使用模板引擎,ThymeleafThymeleaf官网:https://www.thymeleaf.org/
使用Thymeleaf,需要在html文件中导入命名空间的约束,导入之后在IDEA中编写代码会有提示
Thymeleaf常用标签:
| 标签 | 作用 | 示例 |
| th:text | 替换文本 | th:text="${title}" |
| th:value | 替换值 | th:value="${user.name}" |
| th:each | 迭代 | th:each="stu:${user}" |
| th:href | 替换链接 | th:href="@{/index.html}" |
| th:src | 替换资源 | th:src="@{/img/Wechat.jpg}" |
| th:if | 条件判断 | th:if="${isTrue}" |
| th:switch / th:case | 条件判断 | th:switch="${sex}" th:case="'man'" |
| th:insert | 插入 | th:insert="footer :: copy" |
| th:replace | 替换 | th:replace="footer :: copy" |
| th:fragment | 定义片段 | th:fragment="frag (onevar,twovar)" |
$、@ 我大致总结一下:
- $:多为取值,从后端传来的值。
- @:获取资源,获服务器端的静态资源
例如一个网站中,他有很多子网页都有一样的导航栏、侧边栏和底部栏,这样我们就可以将这公共的代码放在一个公共html文件中,需要用取就行。最为方便的是,当需要改变其中一处地方,其它引用代码的页面也一起更改好了。代码示例:
导航栏公共代码:
引用共给代码:
如果需要给代码块中传参数的话(在导航栏的哪个界面,这个界面按钮高亮):
上诉参数是键值对的方式,表示当前在main.html页面,里面识别到的话,主页面按钮高亮。
官方文档补充: Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样;
Message Expressions: #{...}:获取国际化内容
Link URL Expressions: @{...}:定义URL;
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: _



