目录
1、创建Spring Boot项目ThymeleafDemo
2.在全局配置文件里配置Thymeleaf属性
#缓存配置,默认即是true,开发阶段设置为false
spring.thymeleaf.cache = false
#设置模板使用的编码为utf-8
spring.thymeleaf.encoding = UTF-8
#指定为模板使用的模式为html5,默认html
spring.thymeleaf.mode = HTML5
#指定前缀,默认位置为/templates/,可以修改成其它位置
spring.thymeleaf.prefix = classpath:/templates/
#指定模板文件后缀,默认值为.html,可以修改成其它值
spring.thymeleaf.suffix = .html
3、创建登录控制器LoginController
在net.lzz.lesson09包里创建controller子包
在controller子包里创建LoginController控制器
package net.lzz.lesson09.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Calendar;
@Controller
public class LoginController {
@GetMapping("/toLoginPage")
public String toLoginPage(Model model){
model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
return "login";
}
}
4、创建模板文件,获取控制器传来的动态数据
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.tymeleaf.org/">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<span th:text="${currentYear}">今年</span>
<span th:text="${currentYear} + 1">明年</span>
</body>
</html>
5、启动项目,访问http://localhost:8080/toLoginPage
启动