Springboot - Thymeleaf
1. Thymeleaf
概念
Thymeleaf
是一个跟FreeMarker
类似的模板引擎,它可以完全替代 JSP 。相较与其他的模板引擎,它有如下特点:- 动静结合:
Thymeleaf
在有网络和无网络的环境下皆可运行,无网络显示静态内容,有网络用后得到数据替换静态内容 - 与SpringBoot完美整合,
springboot
默认整合thymeleaf
- 动静结合:
1.1 入门案例
实体类、Mapper文件同博文 - 整合mybatis案例
编写接口
- 编写UserService,调用UserMapper的查询所有方法
/**
* User - Service
*
* @author murphy
*/
@Service
public class UserService {
@Resource
private UserMapper userMapper;
public List<User> findAll() {
return userMapper.selectAll();
}
}
- 编写一个
controller
- 返回一些用户数据,放入模型中,等会在页面渲染
/**
* User - Controller
*
* @author murphy
*/
@Controller
public class UserController {
@Resource
private UserService userService;
@RequestMapping("all")
public String all(Model model) {
List<User> list = userService.findAll();
model.addAttribute("users", list);
// 跳转 - classpath:/templates/users.html
return "users";
}
}
- 引入启动器 - 直接引入启动器:
<!-- thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
SpringBoot会自动为Thymeleaf
注册一个视图解析器:
与解析JSP的InternalViewResolver
类似,Thymeleaf
也会根据前缀和后缀来确定模板文件的位置:
- 默认前缀:
classpath:/templates/
- 默认后缀:
.html
所以如果我们返回视图:users
,会指向到classpath:/templates/users.html
一般我们无需进行修改,默认即可。
静态页面
根据上面的文档介绍,模板默认放在classpath
下的templates
文件夹,我们新建一个html
文件放入其中:
编写html
模板,渲染模型中的数据:
注意:把html的名称空间,改成xmlns:th="http://www.thymeleaf.org"
会有语法提示
<!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>