- Thymeleaf概述
Thymeleaf是一个Java模板引擎,支持html、xml、text、javascript、css、raw这几种模型。
使用Thymeleaf首先需要引入命名空间
<html xmlns:th="http://www.thymeleaf.org">
- 基本使用方法
引用web静态资源 Thymeleaf通过”@{}”来引用web静态资源,例如:
<script th:src="@{bootstrap/js/boostrap.min.js}"></script>
-
访问model模型中的数据,例如访问一个user对象的name属性
<span th:text="${user.name}"></span>
-
数据迭代 例如迭代一个userlist集合
使用th:each做循环迭代,并使用${对象.属性}来访问具体的值<tr th:each="user : ${userlist}"> <td th:text="${user.name}">tyrone</td> <td th:text="${user.age}">18</td> </tr>
-
判断是否为空
<tr th:if="${messages.empty}"> <td colspan="3">No messages</td> </tr>
-
在Javascript中访问model模型数据
通过添加th:inline=”javascript”到script标签来访问model模型数据
通过”[[${}]]”这种格式来获取具体的值<script th:inline="javascript"> var user = [[${user}]] console.log(user.name + "\t" + user.age); </script>
webjars统-管理静态资源
Spring boot使用webjars统-管理静态资源 三大理由:
- 将静态资源版本化,刚加有利于升级和维护。
- 剥离静态资源。提高编译速度和打包效率。
- 实现资源共享。有利于前端开发。
"classpath:/META-INF/resources/".
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":当前项目的根路径
二,引入Thymeleaf:
前后端不分离:
- 前端把html页面交付给后端开发。
- 后端使用模板引擎。当年使用最广泛的是jsp
- 然后前后端集成对接。遇到问题前端返工后端返工
- 然后又集成。直到集成成功。
这种模式:
前后端严重的耦合,增加了大量的沟通的成本,影响进度,大大降低了开发的效率。 前后端分离: .
前后端分离不是一种开发模式,web应用的架构模式。 前后端工程师约定好数据交互的接口。 前后端使用http或者其他协议来进行交互 请求。.
- 客户端和服务端采用RESTful交方式进行交互
- 前端端代码库分离
- 并行开发
Thymelemaf使用来开发web和独立环境项目服务java模板引擎 spring官方推荐不包含jsp,
thymeleafIspringmvc视图技术, 以及和spring boot自动化配置集成非常完美,几乎没有什么成本,
**
Tmelemaf特点
**
- 动静结合
- 开箱即用
- 多方言支持:
- 与spring boot完美整合。
HelloWorld Thymelemaf
打包webjars
<!--构建工具,打包时引入-->
<build>
<resources>
<resource>
<directory>${project.basedir}/src/main/resources</directory>
<targetPath>META-INF/resources/</targetPath>
</resource>
</resources>
</build>
引入
<dependency>
<groupId>org.example</groupId>
<artifactId>sous</artifactId>
<version>1.0</version>
</dependency>
页面
<link rel="stylesheet" th:href="@{/webjars/metronic/1.0/cc/all.min.css}">