一、Spring Boot支持的视图技术
Spring Boot框架为简化项目的整体开发,对一些常用的视图技术实现了整合支持,并主要推荐整合模板引擎技术来实现前端页面的动态化内容。
Spring Boot可整合的模板引擎技术
FreeMarker
Groory
Thymeleaf
Mustache
二、Thymeleaf基本语法
相关语法 ,请学习《thymeleaf_3.0.5_中文参考手册.pdf》 提取码:fqpu
1、Thymeleaf常用标签
2、Thymeleaf主要语法
3、Thymeleaf内置对象
4、Thymeleaf模板基本配置
三、Spring Boot整合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.wz.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
Thymeleaf页面缓存设置,默认为true,开发中方便调试应设置为false,上线稳定后应保持默认true。
3、创建登录控制器LoginController
在net.wz.lesson09包里创建controller子包
在controller子包里创建LoginController控制器
用于前端模板页面动态数据替换效果的测试
package net.wz.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 {
/**
* 通过请求“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=