第一个Thymeleaf模板页
1. 添加依赖
spring-boot-starter-thymeleaf:Thymeleaf 自动配置nekohtml:允许使用非严格的 HTML 语法
2. 在 application.yml 中配置 Thymeleaf
spring
:
thymeleaf
:
cache
: false # 开发时关闭缓存
,不然没法看到实时页面
mode
: HTML # 用非严格的 HTML
encoding
: UTF
-8
servlet
:
content
-type
: text
/html
server
:
port
: 80
3. 创建一个 Controller,造一些测试数据并设置跳转
@Controller
public class MainController {
@RequestMapping(value
= {"","/index"},method
= RequestMethod
.GET
)
public String
index(Model model
){
User user
= new User();
user
.setName("huihui");
model
.addAttribute("user",user
);
return "index";
}
}
4. 在 templates 目录下创建 index.html 文件,代码如下:
<!DOCTYPE html SYSTEM
"http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns
="http://www.w3.org/1999/xhtml" xmlns
:th
="http://www.thymeleaf.org">
<!DOCTYPE html
>
<html lang
="en">
<head>
<meta charset
="UTF-8">
<title>Title
</title
>
</head
>
<body>
<span th
:text
= "${user.name}">joker_hui
</span
>
</body
>
</html
>
注意: 修改 html 标签用于引入 thymeleaf 引擎,这样才可以在其他标签里使用 th:* 语法
<!DOCTYPE html SYSTEM
"http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns
="http://www.w3.org/1999/xhtml" xmlns
:th
="http://www.thymeleaf.org">
最后: 在浏览器输入localhost,就可以看到页面的效果