在springboot项目中
(1)引入thymeleaf启动器
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
(2)覆盖配置
springboot自动配置了thymeleaf已经比较完善,但是我们也可以根据需要手动修改application.yaml
springboot自动配置thymeleaf过程
(3)定义UserController(这里省略service,dao,pojo,application.yaml配置,不多赘述)
@Slf4j
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private IUserService userService;
@RequestMapping("findAll")
public ModelAndView findAll(){
ModelAndView mv = new ModelAndView();
List<User> users= userService.queryAll();
mv.addObject("users",users);
mv.setViewName("users");
return mv;
}
}
(4)新建users.html
<html>
标签需要引入约束:xmlns:th="http://www.thymeleaf.org"
- thymeleaf语法和jsp类似
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
<style type="text/css">
table {border-collapse: collapse; font-size: 14px; width: 80%; margin: auto}
table, th, td {border: 1px solid darkslategray;padding: 10px}
</style>
</head>
<body>
<div style="text-align: center">
<span style="color: darkslategray; font-size: 30px">欢迎光临!</span>
<hr/>
<table class="list">
<tr>
<th>id</th>
<th>用户名</th>
<th>出生日期</th>
<th>性别</th>
<th>地址</th>
</tr>
<tr th:each="user : ${users}">
<td th:text="${user.id}">1</td>
<td th:text="${user.username}">zhangsan</td>
<td th:text="${user.birthday}">20</td>
<td th:text="${user.sex}">男</td>
<td th:text="${user.address}">北京王府井</td>
</tr>
</table>
</div>
</body>
</html>
(5)访问效果