thymeleaf
Thymeleaf 是一个现代的服务器端 Java 模板引擎,适用于 Web 和独立环境。
官方文档
https://www.thymeleaf.org/documentation.html
SpringBoot 整合thymeleaf
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.6.2</version>
</dependency>
基本语法
表达式
1. 变量取值
获取请求域,session域,对象等
语法:
${ }
<div th:text="${msg}"></div>
<a th:href="${link}">to baidu</a>
2.选择变量
获取上下文对象值
语法:
*{ }
3.消息
获取国际化等值
语法:
#{ }
4.链接
生成链接
语法:
@{ }
5.片段表达式
jsp:include作用,引入公共页面
语法:
~{ }
字面量
文本值(String)
使用单引号
‘this is an example’
数字(int,float)
0,50,52.6
布尔值
true,false
空值
null
变量
正常写就行
num,title
文本操作
字符拼接
直接使用+运算符
‘this’+‘is’+i+‘example’
变量替换
${ 变量名 }
数学运算
+,-,*,/,%
布尔运算
and,or,!,not
比较运算
< , > ,>= , <= , ==,!=
设置属性值 th:value
<input th:value = "#{}">
基本使用
引入
<html xmlns:th="http://www.thymeleaf.org">
先引入这一段才能使用thymeleaf
ViewController
package com.example.day2.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class ViewController {
@GetMapping("/test")
public String sendMsg(Model model){
model.addAttribute("msg","hello thymeleaf");
model.addAttribute("link","https://www.baidu.com/");
return "success";
}
}
success.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${msg}"></div>
<a th:href="${link}">to baidu</a>
</body>
</html>