一 点睛
Spring Boot提供了大量的模板引擎,包含FreeMarker,Groovy、Thymeleaf、Velocity和Mustache,Spring Boot中推荐使用Thymeleaf作为模板引擎,因为Thymeleaf提供了完美的Spring MVC的支持。
Thymeleaf是一个Java类库,它是一个xml/xhtml/html5的模板引擎,可以作为MVC的Web应用的View层。
Thymeleaf还提供了额外的模块与Spring MVC集成,所有我们可以使用 Thymeleaf完全替代JSP。
二 代码解读
<!-- 将镜头页面转换为动态的视图,需要进行动态处理的元素使用“th:”为前缀 -->
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta content="text/html;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<!-- 通过"@{}"引用Web静态资源,这在JSP下极易出错 -->
<link th:href="@{bootstrap/css/bootstrap.min.css}" rel="stylesheet"/> <!-- 引入bootstrap作为样式控件 -->
<link th:href="@{bootstrap/css/bootstrap-theme.min.css}" rel="stylesheet"/> <!-- 引入bootstrap作为样式控件 -->
</head>
<body>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">访问model</h3>
</div>
<div class="panel-body">
<!-- 通过${}访问模型中的属性,注意,需要处理的动态内容需要加上th:前缀 -->
<span th:text="${singlePerson.name}"></span>
</div>
</div>
<!-- 表达式判断people是否为空。Thymeleaf支持>、 <、 >=、 <=、 ==、 !=作为比较条件,同时也支持将SpringEL表达式语言用于条件中。 -->
<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">
<!-- 使用th:each来做循环迭代(th:each="person:${people},persion作为迭代元素来使用)-->
<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>
</ul>
</div>
</div>
</div>
<script th:src="@{jquery-1.10.2.min.js}" type="text/javascript"></script>
<script th:src="@{bootstrap/js/bootstrap.min.js}"></script><!-- 2 -->
<!-- JavaSript代码访问model的情况 ,使用[[${}]] 格式获得实际值-->
<script th:inline="javascript">
var single = [[${singlePerson}]];
console.log(single.name+"/"+single.age)
function getName(name){
console.log(name);
}
</script>
</body>
</html>
三 参考