文章目录
SpringBoot下使用thymeleaf
1、Thymeleaf是什么
Thymeleaf是一个模板引擎
Thymeleaf简单的跟你说 就是做开发的时候 用来显示前端页面以及数据的这样一个框架
Thymeleaf这个框架 就有点类似于 前面学习的jsp 功能主要就是页面的显示和数据的绑定
2、Thymeleaf能干什么
简单的说、支持很多页面模板(HTML)、以及可以实现以前jsp在页面上实现的所有功能
3、Thymeleaf的使用
3.1、导包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3.2、配置
# 配置模板引擎的这个前缀
spring.thymeleaf.prefix=classpath:/templates/
#配置模板引擎的访问后缀
spring.thymeleaf.suffix=.html
#配置模板引擎的这个模板的类型
spring.thymeleaf.mode=HTML5
#设置模板的内容编码
spring.thymeleaf.encoding=UTF-8
#spring.thymeleaf.content-type=text/html
#配置模板的缓存
spring.thymeleaf.cache=false
3.3、编写controller
/**
* 跳转到bobo这个页面去
* @return
*/
@RequestMapping("toBobo")
public String toBobo(Model model){
model.addAttribute("userName","小王子");
//放入一个对象进去
User user = new User(1, "铁蛋", "110");
model.addAttribute("user",user);
return "bobo";
}
3.4、编写模板页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
this is bobo page And you? <br>
<hr/>
<!--获取单个值-->
用户名是:<span th:text="${userName}"></span>
<span>xxxxx</span><br>
<!--获取对象的值-->
获取到的对象的值是:<br>
用户名: <span th:text="${user.userName}"></span><br>
密码:<span th:text="${user.password}"></span><br>
</body>
</html>