Thymeleaf的简单介绍及用法:
搭建步骤:
-
创建Spring Boot项目,引入Thymeleaf依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
-
编写配置文件,对Thymeleaf模板的页面数据缓存进行设置
thymeleaf页面缓存设置(默认为true),开发中方便调试应设置为false,上线稳定后应保持默认true
spring.thymeleaf.cache=false spring.thymeleaf.encoding=utf-8 spring.thymeleaf.mode=HTML5 spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html
-
创建控制类:@Controller
@Controller public class LoginController { @GetMapping("/toLoginPage") public String toLoginPage(Model model){ model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR)); return "login"; } }
-
创建模板页面并引入静态资源文件
创建一个用户登录的模板页面login.html,部分参考代码如下
<html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>用户登录界面</title> <link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet"> <link th:href="@{/login/css/signin.css}" rel="stylesheet"> </head>
在body标签中通过th:text引入了后台动态传递过来的当前年份currentYear
<button class="btn btn-lg btn-primary btn-block" type="submit">登录</button> <p class="mt-5 mb-3 text-muted">©<span th:text="${currentYear}">2018</span> -<span th:text="${currentYear}+1">2019</span></p>
项目结构图:
-
效果测试
文章评论