主要作用:
1. 解决JSP代码编写过程中过于臃肿的问题.
2. Thymeleaf提供了一种可以被浏览器显示的模板创建方式,可以通过它去创建经过验证XML与HTML模板.开发者只需要通过标签在模板中进行编写就可以轻松的简化显示层的程序逻辑代码.
快速入门
1. 创建一个新的本地模块,暂且叫做module-thymeleaf模块
<module>module-thymeleaf</module>
2. 修改pom.xml文件,添加Thymeleaf依赖库的配置
<dependency>
<groudId>org.springframework.boot</groudId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
这样就完成了基本Thymeleaf语法来实现显示层逻辑处理.
Thymeleaf编程实操
Thymeleaf通过传统的MVC模式进行处理,在定义控制器的时候需要使用@Controller注解来完成.通过操控具体的实体类对象,可以传递相应属性到页面中显示.
1. 建立ThymeleafController控制类,使这个类跳转到Thyemelaf模板页面
@Controller
public class ThymeleafController{
@GetMapping("/root)
public String view(String mid , Model model){
//request属性传递
model.addAttribute("放入你的url","基本需要链接的网址");
//request属性传递包装
model.addAttribute("mid","mid");
//放入你所需要的获取的信息
return "一级目录 / .html ";
}
}
ThymeleafController控制器会跳转到一级目录下的.html页面进行展示,该页面一定是在classpath路径下的配置(可以在application.yml文件中配置).
SpringBoot项目中的Thymeleaf的动态页面需要保存在templates目录中,页面的扩展名默认使用的是*.html,或者使用application.yml文件进行配置.
application.yml的配置
spring:
thymeleaf:
suffix: .html
prefix: classpath:/templates/
*.html页面,用于实现控制层传递属性输出
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>SpringBoot模板渲染</title>
<meta http-equiv="Content-Type" content="text/html:charset=UTF-8"/>
</head>
<body>
<!-- 输出url的属性 -->
<p th:text="'官方文档: ' + ${url}"/>
<!-- 输出mid属性 -->
<p th:text="'用户名:' + ${mid}"/>
</body>
<html>
主要通过<p>元素输出要是显示的内容,通过"th:属性"的形式处理,可以实现Thymeleaf功能,th:text的主要作用是进行文本输出.要想实现request属性中的内容,需要采用"${属性名称}"的语法格式完成.随后启动程序,输出localhost:/view? 就可以实现页面运行的效果.
Thymeleaf语法
<!-- 加法计算 -->
<p th:text="1 + 2"/>
<!-- 字符串连接 -->
<p th:text="'Hello' +'World!'"/>
Thymeleaf模板页面会自动根据运算的数据类型和运算符进行计算.