Thymeleaf模板引擎
1、创建Spring Boot项目ThymeleafDemo
添加项目依赖
查看pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>net.hw.lesson09</groupId>
<artifactId>thymeleafdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ThymeleafDemo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
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.zyb.lesson01包里创建controller子包
在controller子包里创建LoginController控制器
代码
package net.zyb.lesson01.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 {
/**
* 通过请求“toLoginPage”跳转到templates目录下的
* login页面,并把当前年份数据保存到模型对象中
*/
@GetMapping("toLoginPage")
public String toLoginPage(Model model){
model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
return "login"; // 返回逻辑页面视图名称
}
}
4.创建模版文件,获取控制器传来的动态数据
在templates目录下创建模板文件login.html
代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.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
在浏览器里访问http://localhost:8080/toLoginPage