视图技术应用的基材包括(视图技术Thymeleaf-SpringBoot(4))
1.什么是Thymeleaf
Spring Boot 主要支持Thymeleaf 、Freenrtarker 、Mustache 、Groovy Templates 等模板引擎 。
Thymeleaf语法并不会破坏文档的结构 ,所以Thymeleaf模板依然是有效的HTML文档 。模 板还可以被用作工作原型 ,Thymeleaf会在运行期内替换掉静态值。它的模板文件能直接在浏览器 中打开并正确显示页面 ,而不需要启动整个Web应用程序 。
1.1 为什么需要模板引擎
Thymeleaf解决了前端开发人员要和后端开发人员配置一样环境的尴尬和低效 。它通过属性进 行模板渲染 ,不需要引入不能被浏览器识别的新的标签 。页面直接作为HTML文件 ,用浏览器打开页面即可看到最终的效果 ,可以降低前后端人员的沟通成本 。
1.2 使用Thymeleaf
要使用Thymeleaf,首先需要引入依赖 。直接在pom.xml文件中加入以下依赖即可 。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <version>2.0.7.RELEASE</version> </dependency>在模板文件中加入解析 ,在html文件中加入命名空间即可 。
<html lang="en" xmlns:th="http://www.thymeleaf.org/">1.3 配置视图解析器
Spring Boot默认的页面映射路径(即模板文件存放的位置)为 "classpath: /templates/*.html" 。 静态文件路径为 "classpath:/static/" ,其中可以存放层叠样式表CSS( Cascading Style Sheets ) 、 JS (JavaScript)等模板共用的静态文件 。在application.yml文件中 ,可以配置Thymeleaf模板解析器属性
spring: thymeleaf: mode: HTML5 encoding: UTF-8 servlet: content-type: text/html cache: falsespring.thymeleaf.mode:代表 Thymeleaf 模式。
spring.thymeleaf.encodmg:代表 Thymeleaf 编码格式 。
thymeleaf.content-type:代表文档类型 。
thymeleaf.cache:代表是否启用 Thymeleaf 的缓存。
2.基础用法
2.1 引用命名空间
要使用Thymeleaf,则需要先要加入依赖,然后在模板文件中引用命名空间 ,如下:
<html lang="zh" xmlns:th="http://www.thymeleaf.org">之后 ,会进行Thymeleaf模板标签的渲染 。如果用Spring Security作为安全认证,且需要显示登录用户的信息 ,则可以先在视图中加入额外的thymeleaf-extras-springsecurity依赖
<dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity3</artifactId> <version>2.1.0.RELEASE</version> </dependency>然后 在模板文件中加入thymeleaf-extras-springsecurity命名空间 ,具体见以下代码:
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/tyemeleaf-extras-springsecurity5"> <span sec:authorization="name"></span> <span sec:authorize="hasRole(ROLE_ADMIN)">管理员</span> <span sec:authorize="hasRole(ROLE_USER)">普通用户</span>这里特别要注意查看 spring-boot—starter-thymeleaf 依赖和 thymeleaf-extras- springsecurity依赖的版本是否兼容 。如果不兼容,则无法调用登录用户的信息。
2.2 常用th标签
(1)th:text
<div th:text="${name}">name</div>
它用于显示控制器传入的name值 。
如果name不存在 ,要显示默认值 ,则使用以下代码:
<span th:text="${ame} ?:默认值"></span>
(2)th:object
它用于接收后台传过来的对象 ,如以下代码:
th:object="${user}"
(3)th:action
它用来指定表单提交地址 。
<form th:action="@{/article/}+${article.id}" method="post"></form>
(4)th:value
它用对象将id的值替换为value的属性 。
<input type="text" th:value="${article.id}" name="id"/>
(5)th:field
它用来绑定后台对象和表单数据 。Thymeleaf里的"th:field"等同于"th:name"和"th: valued"其具体使用方法见以下代码:
<input type="text" name="title" th:field="${fields}"/>
2.3 Thymeleaf 中的 URL 写法
Thymeleaf是通过语法@{…}来处理URL的 ,需要使用"th:href"和"th:src"等属性 ,如以下代码
<a th:href="https://www.cnblogs.com/liwenruo/p/@{http://www.thymeleaf.org}">绝对路径</a> <a th:href="https://www.cnblogs.com/liwenruo/p/@{/}">相对路径</a> <a th:href="https://www.cnblogs.com/liwenruo/p/@{css/bootstrap.min.css}">默认访问static下的css文件夹</a>2.4用Thymeleaf进行条件求值
Thymeleaf通过 "th:if" 和 "th:unless" 属性迸行条件判断 。在下面的例子中 ,<a>标签只有 在 "th:if" 中的条件成立时才显示 。
<a th:href="https://www.cnblogs.com/liwenruo/p/@{/login}" th:if="${session.user == null}">Login</a>
"th:unless" 与 "th:if" 恰好相反 ,只有当表达式中的条件不成立时才显示其内容 。在下方代码中 ,如果用户session为空 ,则不显示登录(login )链接 。
<a th:href="https://www.cnblogs.com/liwenruo/p/@{/login}" th:unless="${session.user == null}">Login</a>
2.5 Switch
<div th:switch="${book.getId()}"> <p th:case="ADMIN">管理员</p> <p th:case="VIP">vip会员</p> <p th:case="*">普通会员</p> </div>上述代码的意思是:如果用户角色(role)是admin,则显示“管理员 ”;如果用户角色是vip, 则显示"vip会员 ”;如果都不是,则显示“普通会员” ,即使用“* ”表示默认情况 。
2.6 Thymeleaf中的字符串替换
有时需要对文字中的某一处地方进行替换 ,可以通过字符串拼接操作完成,如以下代码:
<span th:text="欢迎,+${book.getUsername()}+!"></span>
或者:
<span th:text="|欢迎,${book.getUsername()}!|"></span>
上面的第2种形式限制比较多 ,|...|中只能包含变量表达式${...},不能包含其他常量 、条件表达式等。
2.7 Thymeleaf的运算符
1.算数运算符 。
如果要在模板中进行算数运算 ,则可以用下面的写法 。以下代码表示求加和取余运算。
<span th:text="9*3"></span>
2.条件运算符
下方代码演示了 if判断,表示:如果从控制器传来的role值等于“admin ” ,则显示 "欢迎您, 管理员";如果role值等于 "vip" ,则显示 "欢迎您 ,vip会员"
<div th:if="${book.getUsername()} eq admin"> <span>欢迎您 ,管理员</span> </div> <div th:if="${book.getUsername()} eq vip"> <span>欢迎您 ,vip</span> </div>eq是判断表达式 ,代表等于 。其他的判断表达式如下 。
gt:大于。
ge:大于或等于 。
eq:等于 。
It:小于 。
le:小于或等于 。
ne:不等于 。
3.判断空值
可以使用if来判断值是否为空 ,如以下代码:
不为空
<span th:if="${book.getUsername()}!=null">为空</span>2.8 Thymeleaf公用对象
Thymeleaf还提供了一系列公用(utility)对象 ,可以通过"#"直接访问 ,如以下用法
格式化时间:
<td th:text="${#dates.format(data,yyyy-MM-dd HH:mm:ss)}">格式化时间</td>
判断是不是空字符串:
<span th:if="${#strings.isEmpty(data)}">空</span>
是否包含(分大小写):
<span th:if="${#strings.contains(book.getUsername(),admin)}">包含</span>
3. 处理循环遍历
3.1 遍历对象(object)
在开发过程中,经常会遇到遍历对象的情况 ,可以通过 th:each="Object:$(Objects}"标签来处理 。以下代码是遍历从控制器中传来的书籍对象 。
<div th:each="book:${book}"> <li th:text="${book.getUsername()}">姓名</li> <li th:text="${book.getPassword()}">密码</li> </div>3.2 遍历分页(page)
分页也是极为常见的开发需求 。在Thymeleaf中,可以通过 th:each="item : ${page.content}"标签来处理page对象 。如以下代码
<div th:each="item:${page.content}"> <li th:text="${item.id}">id</li> <li th:text="${item.title}">title</li> </div>3.3 遍历列表(list)
要处理list,也使用 th:each="item:${list}"标签来实现。
<div th:each="item:${list}"> <li th:text="${item.username}">id</li> <li th:text="${item.password}">title</li> </div>3.4 遍历数组(array)
使用 th:each="item:${arrays}"标签来遍历数组 ,如以下代码:
<div th:each="ArrayList:${ArrayList}"> <li th:text="${ArrayList}">id</li> </div>3.5 遍历集合(map)
集合通过 th:text="${item.key}"显示集合的 key,通过 th:text="${item.value}" 显示集合的值,如以下代码:
<div th:each="map:${map}"> <li th:text="${map.key}"></li> <li th:text="${map.value}"></li> </div>4. 处理公共代码块
一个网页的结构基本可以分为上(header ) 、中(body ) 、下(footer)三个部分 。在一般情况 下 ,header和footer的信息在各个页面都会重复显示 ,如果每个页面都复制一份代码则太麻烦了 。设计Thymeleaf的团队也考虑到代码复用的问题,提供了 "th:fragment" "th:include" 和 "th:replace"标签用来处理重复的代码块。具体用法如下 。
4.1 用fragment标记重复代码块
可以通过"th:fragment="header" 标签来标记重复代码块 ,如以下代码
<div class="footer" id="header" th:fragment="header"> 公共header </div> <div class="footer" id="footer" th:fragment="footer"> 公共footer </div>4.2 调用重复代码块
在需要调用的地方 ,用"th:include"或"th:replace"标签根据fragment值来调用 ,如以下代码:
其中~{html文件名:: 通过fragment起的别名}
<div th:replace="~{test :: header}"></div> <div th:include="~{test :: footer}"></div>"th:include"和 "th:replace" 标签都可以调用公共代码 。它们的区别如下。
th:replace:替换当前标签为模板中的标签 。比如上面用replace标签 ,则代码替换为:<div class="header">
公共header
</div>
th:include:只加载模板的内容 。比如上面用include标签 ,则代码替换为:<div>
公共footer
</div>
5. 处理分页
在MVC开发过程中 ,分页也是常用的功能 。Thymeleaf可以处理由控制器传入的分页参数 。
1.用控制器传入page对象
Pageable pageable = PageRequest.of(start,limit,sort); Page<Book> page = articleRepository.findAll(pageable); ModelAndView modelAndView = new ModelAndView("/index"); modelAndView.addObject("page",page); return modelAndView;2.用Thymeleaf接收page对象并处理
<div> <a th:href="https://www.cnblogs.com/liwenruo/p/@{/test(start=0)}">[首页]</a> <a th:if="${not page.isFirst()}" th:href="https://www.cnblogs.com/liwenruo/p/@{/test(start=${page.number-1})}">[上页]</a> <a th:if="${not page.isLast()}" th:href="https://www.cnblogs.com/liwenruo/p/@{/test(start=${page.number+1})}">[上页]</a> <a th:href="https://www.cnblogs.com/liwenruo/p/@{/test(start=${page.totalPages-1})}">[末页]</a> </div>6. 验证和提示错误消息
大多数表单信息都需要逬行字符串的验证 ,以及提供错误消息反馈 。Thymeleaf提供了几种提示错误信息的方法 。
6.1字段错误信息提示
<div> <span>email:</span> <span><input type="text" th:field="*{email}" /></span> <span class="warn" th:if="${#fields.hasErrors(email)}" th:errors="*{email}">邮箱错误</span> </div>6.2 提示所有错误
<ul> <li th:each="err:${#fields.errors(*)}" th:text="*{err}">邮箱错误</li> </ul>创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!