前言:springboot官方推荐Thymeleaf作为前端,并不支持jsp。Thymeleaf的后缀是html,因此可以用浏览器打开,但它还可以在html原型上添加额外属性。
1. Springboot集成Thymeleaf
1.1 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
1.2 添加配置
spring:
thymeleaf:
cache: false # 是否开启缓存,默认true
prefix: classpath:/templates/ # 模板文件位置
encoding: UTF-8 #编码
suffix: .html #模板后缀
mode: HTML #模板
1.3 Thymeleaf页面
标签与HTML基本类似,但需要注意:
(1)必须引入thymeleaf
<html lang="en" xmlns:th="https://www.thymeleaf.org/">
(2)在配置文件中配置模板文件位置
(3)默认后缀.html,也可以改成别的
2. Thymeleaf表达式
2.1 变量表达式
获取后台变量:
<p th:text="${name}">hello</p>
th表示是thymeleaf,使用${}获取变量
2.2 选择表达式
先定义后获取属性:
<div th:object="${session.user}">
<p>Name:<span th:text="*{firstname}"></span></p>
先th:object获取user,再用*{}获取user属性
2.3 URL
使用@{}:
<div th:style="backgroud:url('+@{${imageurl}}+');">