springboot默认不支持JSP,所以需要引入第三方模板引擎技术实现页面渲染
整合thymeleaf需要引入starter依赖
<!--引入thymeleaf依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency
所有的thymeleaf页面都是html后缀,并且应该放在templates目录下,而且在html标签中加入名称空间
xmlns:th="http://www.thymeleaf.org"
所有的标签在thymeleaf中都用其对应的th:
的前缀写法
基本使用
在jsp中,使用request作用域中的变量我们使用${}的形式来使用,在thymeleaf中也是同样的方式
<h1 th:text="${msg}"></h1>
thymeleaf中可以使用@{}的形式引用链接
<!--改变一个属性的值 使用 th:href 使用$符号获取的是link对应的value-->
<a href="www.baidu.com" th:href="${link}">去百度</a>
<!--使用@符号相当于是内部的内容直接就是一个地址字符串,之后会直接把这个字符串拼接上去-->
<a href="www.baidu.com" th:href="@{link}">去百度</a>
当我们在application.properties配置文件中使用server.servlet.context-path属性给项目设置地址之后,使用@符号取地址,thymeleaf就会自动给地址前加上项目的地址,但是必须是绝对路径的写法(以/开头的地址写法),相对路径就是不以斜杠开头
静态导入
我们可以将页面的公共部分进行抽取,在common页面中存放公共的部分,语法为
<!--name就是名称-->
<div th:fragment="name">
公共部分
</div>
在使用的时候有语法供我们选择 th:insert th:replace th:include
语法
<div th:insert="~{footer :: copy}"></div>
或者
<div th:insert="footer :: copy"></div>
三者的区别
<body>
...
<div th:insert="footer :: copy"></div> 将公共部分连同标签一同导入
<div th:include="footer :: copy"></div> 将公共部分的标签内部的内容导入
<div th:replace="footer :: copy"></div> 将原来的标签直接替换为公共部分的标签
</body>
对应的结果
<body>
...
<div>
<footer>
© 2011 The Good Thymes Virtual Grocery
</footer>
</div>
<div>
© 2011 The Good Thymes Virtual Grocery
</div>
<footer>
© 2011 The Good Thymes Virtual Grocery
</footer>
</body>
循环
语法
<tr class="gradeX" th:each="user,stats : ${users}">
<td th:text="${stats.count}"></td>
<td th:text="${user.username}"></td>
<td th:text="${user.password}"></td>
</tr>
在循环变量的后面加上一个status就可以使用thymeleaf中自带的一些变量,例如count表示计数,从1开始