新建SpringBoot项目
选择Thymeleaf和web依赖点击finish
创建示例bean
package com.boot.entity;
public class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
引入bootstrap和jquery 放置src/main/resources/static目录下
在src/main/resources/templates目录下创建演示页面
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta content="text/html;charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" >
<link th:href="@{bootstrap-3.3.7-dist/css/bootstrap.min.css}" rel="stylesheet"/>
<link th:href="@{bootstrap-3.3.7-dist/css/bootstrap-theme.min.css}" rel="stylesheet"/>
<title>演示页面</title>
</head>
<body>
<div class="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>
<div th:if="${not #lists.isEmpty(people)}">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">列表 </h3>
</div>
</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>
<button class="btn" th:onclick="getName('${person.name}')">获得名字</button>
</li>
</ul>
</div>
</div>
<script type="text/javascript" th:src="@{jquery-3.4.1.js}"></script>
<script th:src="@{bootstrap-3.3.7-dist/js/bootstrap.min.js}"></script>
<script th:inline="javascript">
var single=[[${singlePerson}]];
console.log(single.name+"/"+single.age);
function getName(name){
console.log(name);
}
</script>
</body>
</html>
编写测试控制器 启动
package com.boot;
import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.boot.entity.Person;
@SpringBootApplication
@Controller
public class SpringbootThymeleafApplication {
@RequestMapping("/")
public String index(Model model) {
Person single=new Person("tom",20);
List<Person> list=new ArrayList<Person>();
Person p1=new Person("aa",11);
Person p2=new Person("bb",22);
Person p3=new Person("cc",33);
list.add(p1);
list.add(p2);
list.add(p3);
model.addAttribute("singlePerson", single);
model.addAttribute("people", list);
return "index";
}
public static void main(String[] args) {
SpringApplication.run(SpringbootThymeleafApplication.class, args);
}
}
浏览器输入http://localhost:8080 查看效果