SpringBootWeb开发-4
上一级页面:ssm-spring-boot速成学习索引
前言
43、视图解析-Thymeleaf初体验
Thymeleaf is a modern server-side Java template engine for both web and standalone environments.
Thymeleaf’s main goal is to bring elegant natural templates to your development workflow — HTML that can be correctly displayed in browsers and also work as static prototypes, allowing for stronger collaboration in development teams.
With modules for Spring Framework, a host of integrations with your favourite tools, and the ability to plug in your own functionality, Thymeleaf is ideal for modern-day HTML5 JVM web development — although there is much more it can do.——Link
thymeleaf使用
引入Starter
1 | <dependency> |
自动配置好了thymeleaf
1 |
|
自动配好的策略
-
所有thymeleaf的配置值都在 ThymeleafProperties
-
配置好了 SpringTemplateEngine
-
配好了 ThymeleafViewResolver
-
我们只需要直接开发页面
1 | public static final String DEFAULT_PREFIX = "classpath:/templates/";//模板放置处 |
编写一个控制层:
1 |
|
/templates/success.html
:
1 |
|
1 | server: |
这个设置后,URL要插入/app
, 如http://localhost:8080/app/hello.html
。
基本语法
表达式
表达式名字 | 语法 | 用途 |
---|---|---|
变量取值 | ${…} | 获取请求域、session域、对象等值 |
选择变量 | *{…} | 获取上下文对象值 |
消息 | #{…} | 获取国际化等值 |
链接 | @{…} | 生成链接 |
片段表达式 | ~{…} | jsp:include 作用,引入公共页面片段 |
字面量
- 文本值: ‘one text’ , ‘Another one!’ ,…
- 数字: 0 , 34 , 3.0 , 12.3 ,…
- 布尔值: true , false
- 空值: null
- 变量: one,two,…. 变量不能有空格
文本操作
- 字符串拼接: +
- 变量替换: |The name is ${name}|
数学运算
- 运算符: + , - , * , / , %
布尔运算
- 运算符: and , or
- 一元运算: ! , not
比较运算
- 比较: > , < , >= , <= ( gt , lt , ge , le )
- 等式: == , != ( eq , ne )
条件运算
- If-then: (if) ? (then)
- If-then-else: (if) ? (then) : (else)
- Default: (value) ?: (defaultvalue)
特殊操作
- 无操作: _
设置属性值-th:attr
- 设置单个值
1 | <form action="subscribe.html" th:attr="action=@{/subscribe}"> |
- 设置多个值
1 | <img src="../../images/gtvglogo.png" |
官方文档 - 5 Setting Attribute Values
迭代
1 | <tr th:each="prod : ${prods}"> |
1 | <tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'"> |
条件运算
1 | <a href="comments.html" |
1 | <div th:switch="${user.role}"> |
属性优先级
Order | Feature | Attributes |
---|---|---|
1 | Fragment inclusion | th:insert th:replace |
2 | Fragment iteration | th:each |
3 | Conditional evaluation | th:if th:unless th:switch th:case |
4 | Local variable definition | th:object th:with |
5 | General attribute modification | th:attr th:attrprepend th:attrappend |
6 | Specific attribute modification | th:value th:href th:src … |
7 | Text (tag body modification) | th:text th:utext |
8 | Fragment specification | th:fragment |
9 | Fragment removal | th:remove |
官方文档 - 10 Attribute Precedence