Thymeleaf是一个Java类库,它是一个xml/xhtml/html5的模板引擎,能够做为MVC的Web引用的View层。javascript
Thymeleaf还提供了额外的模块与SpringMVC集成,所以推荐使用Thymeleaf来替代JSPcss
一、引入Thymeleafhtml
下面的diam是一个基本的Thymeleaf模板页面,在这里引入Boostrap(做为样式控制)和jQuery(DOM操做)html5
<html xmlns:th="http://www.thymeleaf.org"><!--1--> <head> <meta content="text/html;charset=UTF-8"/> <link th:src="@{bootstrap/css/bootstrap.min.css}" rel="stylesheet"/><!--2--> <link th:src="@{bootstrap/css/bootstrap-theme.min.css}" rel="stylesheet"/><!--2--> </head> <body> <script th:src="@{jquery-1.10.2.min.js}" type="text/javascript"></script><!--2--> <script th:src="@{bootstrap/css/bootstrap.min.js}"></script><!--2--> </body> </html>
Analysize:java
a、经过xmlns:th=http://www.thymeleaf.org命名空间,将镜头页面转换为动态的视图。须要进行动态处理的元素将使用“th:”为前缀;jquery
b、经过“@{}”引用web静态资源,这在JSP下是极易出错的。web
二、访问model中的数据bootstrap
经过“${}”访问model中的属性,这和JSP极为类似spa
<div lass = "panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">访问model</h3> </div> <div class="panel-body"> <span th:text="${singlePerson.name}"></span> </div> </div>
Analysize:code
使用<span th:text="${singlePerson.name}"></span>访问model中的singlePerson的name属性。注意:须要处理的动态内容须要加上“th:”前缀。
三、model中的数据迭代
Thymeleaf的迭代和JSP的写法类似
<div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">列表</h3> </div> <div class="panel-body"> <ul class="list-group"> <li class="list-group-item" th:each="person:${people}"> <span th:text="${person.name}"></span> <span th:text="${person.age}"></span> </li> </ul> </div> </div>
Analysize:
使用th:each来作循环迭代(th:each="person:${people}"),person做为迭代元素来使用。而后像上面同样访问迭代元素中的属性。
四、数据判断
<div th:if="${not #lists.isEmpty(people)}"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title">列表</h3> </div> <div class="panel-body"> <ul class="list-group"> <li class="list-group-item" th:each="person:${people}"> <span th:text="${person.name}"></span> <span th:text="${person.age}"></span> </li> </ul> </div> </div> </div>
Analysize:
经过${not#lists.isEmpty{people}}表达式判断people是否为空。Thymeleaf支持>、<、>=、<=、==、!=做为比较条件,同时也支持将SpringEL表达式语言用于条件中。
五、在JavaScript中访问model
在项目中,须要在JavaScript访问model中的值,在Thymeleaf里实现代码以下:
<script th:inline="javascript"> var single = [[${singlePerson}]]; console.log(single.name + "/" + single.age) </script>
Analysize:
经过th:inline="javascript"添加到script标签,这样JavaScript代码便可访问model中的属性
经过“[[${}]]”格式得到实际的值
还有一种时须要在html的代码里访问model中的属性,例如须要在列表后单击每一行后面的按钮得到model中的值,可作以下处理:
<li class="list-group-item" th:each="person:${people}"> <span th:text="${person.name}"></span> <span th:text="${person.age}"></span> <button class="btn" th:onclick="'getName(\'' + ${person.name} + '\');'">得到名字</button> </li>
Analysize:
注意格式th:onclick="'getName(\"+${person.name} + '\');'"。
六、其余知识
更多完整的Thymeleaf的知识,能够查看https://www.thymeleaf.org/官网