Thymeleaf 官方解释:
Thymeleaf是一个用于web和独立环境的现代服务器端Java模板引擎。
Thymeleaf的主要目的是将优雅的自然模板引入到您的开发工作流中——以使HTML可以在浏览器中正确显示,也可以
作为静态原型使用,从而在开发团队中实现更强的协作。
使用Spring Framework的模块,一个用您最喜欢的工具集成的主机 以及插入您自己功能的能力,Thymeleaf是现代HTML5 JVM
web开发的理想选择——尽管它还可以做更多事情。
Demo
1.Idea下新建一个springboot项目 ,添加依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
2.新建一个Person实体类:
public class Person { private String name; private Integer age; public Person(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
3.测试Controller:
@Controller public class Test { @RequestMapping("/testThymeleaf") public String index(Model model){ Person single=new Person("Eminem",0); List<Person> people=new ArrayList<Person>(); Person p1=new Person("Kobe",1); Person p2=new Person("James",2); Person p3=new Person("Jordan",3); people.add(p1); people.add(p2); people.add(p3); model.addAttribute("singlePerson",single); model.addAttribute("people",people); return "index"; } }
4.templates下新建一个 index.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <meta name="viewport" content="width=device-width,initial-scale=1"/> <link th:href="@{bootstrap/css/bootstrap.min.css}" rel="stylesheet"/> <link th:href="@{bootstrap/css/bootstrap-theme.min.css}" rel="stylesheet"/> <meta charset="UTF-8"/> <title>Title</title> </head> <body> <div class="panel panel-primary"> <div th:if="${not #lists.isEmpty(people)}"> <div class="panel panel-primary"> <h3 class="panel-title">列表</h3> </div> <div class="panel-body"> <span th:text="${singlePerson.name}"></span> </div> <div class="panel-body"> <ul class="panel-group"> <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> <script th:inline="javascript"> function getName(name) { console.log(name); } </script> </body> </html>
5.启动项目,访问http://localhost:8080/testThymeleaf ,结果如下:
代码下载地址:https://github.com/liuchunbo24/Springboot-Thymeleaf-Demo