Thymeleaf基本使用
使用Thymeleaf完成数据的页面展示
创建Spring Boot项目,引入Thymeleaf依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
编写全局配置文件
#thymeleaf页面缓存设置(默认true),开发方便调试应设为false,上线稳定后应保持默认true
spring.thymeleaf.cache = false
#编码格式
spring.thymeleaf.encoding = UTF-8
#模板样式
spring.thymeleaf.mode = HTML
#指定模板页面路经
#spring.thymeleaf.prefix = classpath:/resources/templates/
#spring.thymeleaf.check-template=false
#spring.thymeleaf.check-template-location=false
#指定模板页面的后瑞名
spring.thymeleaf.suffix = .html
创建Web控制类
创建controller包,并在该包下创建一个用与前端模板页面动态数据替换效果测试的访问实体类LoginController
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";
}
}
toLoginPage()方法向登录页面login.html跳转时,携带了表示当前年份信息的currenYear.
创建模板页面并引入静态资源文件
在resources的templates目录下创建一个用户登录的模板页面login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户登录界面</title>
<link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
<link th:href="@{/login/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center">
<form class="form-signin">
<img class="mb-4" th:src="@{/login/img/login.jpg}" width="72" height="72">
<h1 class="h3 mb-3 font-weight-noemal">请登录</h1>
<input type="text" class="form-control"
placeholder&#