1.Thymeleaf介绍
1.1.什么是Thymeleaf
Thymeleaf [taɪm]是一个跟 Velocity、FreeMarker 类似的用Java语言编写的模板引擎,它基于模板和数据生成输出文本(HTML网页、WORD、XML,PDF或Java等)。
2.2.为什么要使用Thymeleaf
两方面影响用户访问速度:
1、数据库查询
使用缓存
2、服务器编译jsp页面
可以使用Thymeleaf、Freemarker实现网页静态化。
2.3.Thymeleaf 的启动器
<!-- thymeleaf的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.Thymeleaf 入门
2.1.创建工程
03_springboot_thymeleaf
2.2.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 http://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.1.6.RELEASE</version>
</parent>
<groupId>com.qf</groupId>
<artifactId>03_springboot_thymeleaf</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- springBoot的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- thymeleaf的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
</project>
2.3.thymeleaf
hymeleaf也会根据前缀和后缀来确定模板文件的位置:
- 默认前缀:
classpath:/templates/
- 默认后缀:
.html
Thymelaef特点:
-
语法:通过他特定标签操作html属性
-
目录位置:src/main/resources/templates
-
后缀名:.html
-
注意,把html 的名称空间,改成:
xmlns:th="http://www.thymeleaf.org"
会有语法提示
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Thymeleaf入门</title>
</head>
<body>
<span th:text="Hello"></span>
<hr/>
<span th:text="${msg}"></span>
</body>
</html>
2.4.controller
@Controller
public class ShowController {
@RequestMapping("/show1")
public String show1(Model model){
model.addAttribute("msg","师姐你好!!!");
return "hello";
}
}
2.4.启动类
package com.qf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
*Thymeleaf入门案例
*/
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
2.5.测试
3.Thymeleaf语法详解
3.1.变量输出
3.1.1.th:text
<span th:text="Hello"></span>
<hr/>
<span th:text="${msg} "></span>
3.1.2.th:value
<input type="text" name="username" th:value="${msg}"/>
3.2.日期和字符串处理
Thymeleaf 内置对象
注意语法:
1.调用内置对象一定要用#
2.大部分的内置对象都以 s 结尾 strings、numbers、dates
日期处理:
<input type="text" name="birth" th:value="${#dates.format(birth,'yyyy-MM-dd')}"/>
字符串处理:
<input type="text" name="msg" th:value="${#strings.substring(msg,0,6)}"/>
3.3.条件判断
3.3.1.th:if
3.4.迭代遍历
3.4.1.th:each
3.5.URL表达式
th:href
th:src
3.5.1.url表达式语法
基本语法:@{}
3.5.2.URL的相对路径
3.5.2.1.相对于当前项目的根
3.5.2.2.相对于服务器路径的根
效果:
3.5.3.在 url中实现参数传递
3.5.3.1.问号形式传参
3.5.3.2.restful风格传参