`

Thymeleaf在spring boot中快速上手

阅读更多
Thymeleaf 是一个页面模板引擎(独立的)(spring boot推荐的模板引擎),可以完全替代 JSP ,使用html+thymeleaf的方式可以在 静态页面中加入动态内容。本文抛砖引玉,讲解spring boot中集成thymeleaf的基本步骤,以及thymeleaf基本使用(附件中附有后端和前端的源码文件)
特点
1.页面内容动静分离 前端后端工作分离
2.与spring boot集成较好:Spring Boot默认就是使用thymeleaf模板引擎的,如果使用SpringBoot框架开发,使用thymeleaf可以省去了很多繁琐的配置步骤
3.在有网络和无网络的环境下皆可运行
4.如果要让页面改动及时生效(不重启服务器),需要在spring boot配置文件里关闭thymeleaf的缓存
spring.thymeleaf.cache=false
 
原理:通过html属性嵌入thymeleaf的动态内容,浏览器会自动忽略不认识的属性,但是不能自动忽略不认识的标签(元素)
 
注意:thymeleaf会对html标签严格检查,虽然可以关闭语法严格检查,但最好还是养成好习惯,比如标签一定要结束(不管是有体标签还是无体标签)
 
Spring boot中集成thymeleaf:
1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
 
2.在resources下创建一个templates目录,用于放置所有动态页面(html+thymeleaf)
3.在创建的html中引入thymeleaf命名空间
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
 
常用表达式
1)变量表达式,从作用域里取值(与EL类似)
${msg}
如果后台没有传过来数据,那么将什么都不显示
 
2)选择表达式,通常同变量表达式配合使用
*{}
选择表达式计算的是指定的对象(th:object属性绑定的对象(预定义)),而不是整个环境变量映射
比如:<div th:object="${myUser1}"> <!--来自于后台作用域对象-->
<!--以下是myUser1的两个属性-->
id:<span th:text="*{userId}"></span><br/>
userName:<span th:text="*{userName}"></span>
</div>
 
3) URL表达式:@{}(类似于JSTL中的<c:url/>)
@{/disaplayTable(paramId=${paramId})}
 
常用属性
th:text=
th:object=
th:href=
th:action=
th:if=
th:each="user : ${userModel.userList}"
th:replace=
 
1)th:action
定义后台控制其路径,类似标签的action属性
<form id=”login-form” th:action = “@{/login}”>...</form>
 
2)th:each迭代器
<table>
<!--对象遍历,功能类似jstl中的foreach标签-->
<tr th:each="oneUser:${userList}">
<td th:text="${oneUser.userId}"></td>
<td th:text="${oneUser.userName}"></td>
</tr>
</table>
 
3)th:field
常用于表单字段的绑定.通常与th:object一起使用.属性绑定
<form th:action="@{/helloThymeleaf8}" th:object="${user}" method="post" th:method="post">
<input type="text" th:field="*{userId}"/>
<input type="text" th:field="*{userName}"/>
<input type="submit" value="提交"/>
</form>
 
4)th:href(之前已经演示过了)
定义超链接,类似标签的href属性,value值的形式为@{/logout}
<a th:href="@{/logout}" class="signOut"></a>
 
5)th:Object(之前演示过了)
用于表单数据对象的绑定,将表单绑定到后台Conroller的一个实体对象参数(注意名字要对应上)。常与th:field一起使用进行表单数据的绑定
 
<form th:action="@{/hello/helloHtml5}" th:object="${user}" method="post" th:method="post">
姓名:<input type="text" th:field="*{name}"/>
年龄:<input type="text" th:field="*{age}"/>
<input type="submit" value="提交"/>
</form>
 
6)th:text文本显示(之前在表达式中演示过了)
 
<td class="text" th:text="${username}" ></td>
 
7)th:src外部资源的引入
类似于script标签的src属性,常与@{}一起使用
<script th:src="@{/resources/js/jquery/jquery.json-2.4.min.js}"
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics