导入pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Spring Boot官方文档建议在开发时将缓存关闭,那就在application.properties文件中加入下面这行
spring.thymeleaf.cache=false
正式环境还是要将缓存开启的
如图:
我的是把application.properties改成application.yml文件后的格式
Controller
@Controller
public class IndexController {
@RequestMapping("/user/list")
public ModelAndView list(){
ModelAndView modelAndView=new ModelAndView();
modelAndView.setViewName("user/list");
modelAndView.addObject("title","aa");
List list = new ArrayList();
list.add(new User(1,"欧几把枪","蒙牛代言人"));
list.add(new User(2,"欧几把枪2","蒙牛代言人2"));
modelAndView.addObject("users",list);
return modelAndView;
}
}
entity
public class User {
private Integer uid;
private String username;
private String bak;
public User() {
}
public User(Integer uid, String username, String bak) {
this.uid = uid;
this.username = username;
this.bak = bak;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getBak() {
return bak;
}
public void setBak(String bak) {
this.bak = bak;
}
}
html页面
这行加上之后就会有提示<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
</head>
<body>
<h1 th:text="${title}"></h1>
<h1>循环</h1>
<table border="1px" width="600px">
<thead>
<tr>
<td>用户id</td>
<td>用户名</td>
<td>用户描述</td>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.uid}"></td>
<td th:text="${user.userName}"></td>
<td th:text="${user.desc}"></td>
</tr>
</tbody>
</table>
<h1>下拉框</h1>
<select>
<option th:each="user : ${users}" th:value="${user.uid}" th:text="${user.userName}"></option>
</select>
</body>
</html>
运行结果如下