<!-- 模板引擎thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--热部署 使应用程序开发体验更加愉快-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-devtools</artifactId>
<!--可选的,一定要写一个true,有这个才算是导入了-->
<optional>true</optional>
</dependency>
一、前端使用
1、引入Thymeleaf
<!--引入名称空间,将静态界面转换为动态视图。需要进行动态处理的元素将使用“th:”为前缀-->
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta content="text/html;charset=UTF-8"/>
<!--通过“@{}”引用Web静态资源,这在JSP下是极易出错的-->
<link th:src="@{bootstrap/css/bootstrap.min.css}" rel="stylesheet"/>
<link th:src="@{bootstrap/css/bootstrap-theme.min.css}" rel="stylesheet"/>
<body>
<script th:src="@{jquery-1.10.2.min.js}" type="text/javascript"></script>
<script th:src="@{bootstrap/js/bootstrap.min.js}"></script>
</body>
</head>
</html>
2、访问model中的数据
<span th:text="${singlePerson.name}"></span>
3、model中的数据迭代
<ul>
<li th:each="person:${people}">
<span th:text="${person.name}"></span>
<span th:text="${person.age}"></span>
</li>
</ul>
4、数据判断
<div th:if="${not #lists.isEmpty(people)}">
下如果lists的isEmpty方法判断people数组返回true,则表示为空,则不显示内容,前面加一个not,把值变为false
</div>
通过${not #lists.isEmpty(people)}
表达式判断people是否为空。Thymeleaf支持>、<、>=、<=、==、!= 作为比较条件,也支持将SpringEL表达式语句用于条件之中。
5、JS中访问model
<script th:inline="javascript">
var single = [[${singlePerson}]];
//通过 “[[${}]]” 格式获得实际的值
console.log(single.name+"/"+single.age);
</script>
6、官网
http://www.thymeleaf.org
二、SpringBoot后端使用
1、静态页面放置
默认原则,静态页面应放置在 src/main/resources/templates 下。在 src/main/resources/templates 下新建 index.html
2、数据准备
@Controller
public class Test{
@RequestMapping("/");
public String index(Model model){
Person single = new Person("aa",11);
List<Person> people = new ArrayList<Person>();
people.add(new Person("xx",11));
people.add(new Person("yy",22));
people.add(new Person("zz",33));
model.addAttribute("singlePerson",single);
model.addAttribute("people",people);
return "index";
}
}