SpringBoot——Thymeleaf模板引擎使用详解

什么是Thymeleaf

Thymeleaf是一个用于web和独立环境的现代服务器端Java模板引擎。Thymeleaf的主要目标是将优雅自然的模板引入到您的开发工作流程中——HTML可以在浏览器中正确显示,也可以作为静态原型工作,从而在开发团队中实现更强大的协作。
有了Spring框架的模块、与您喜爱的工具的大量集成,以及插入您自己的功能的能力,Thymeleaf是现代HTML5 JVM web开发的理想选择——尽管它可以做的还有很多。

如何在自己的项目中使用Thymeleaf

第一步:去https://docs.spring.io/spring-boot/docs/2.1.6.RELEASE/reference/html/using-boot-build-systems.html#using-boot-starter这个网站找到Thymeleaf的对应starter启动器,然后poml.xml文件中的两个关于Thymeleaf的依赖复制下来,粘贴到你项目的pom.xml文件的<dependency>标签下

如下图:

 pom.xml

1 <dependency>
2     <groupId>org.thymeleaf</groupId>
3     <artifactId>thymeleaf-spring5</artifactId>
4 </dependency>
5 <dependency>
6     <groupId>org.thymeleaf.extras</groupId>
7     <artifactId>thymeleaf-extras-java8time</artifactId>
8 </dependency>

 这里我们的Thymeleaf是基于3.x开发的

第二步:编写Controller类

 1 package com.lzp.controller;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.ui.Model;
 5 import org.springframework.web.bind.annotation.RequestMapping;
 6 
 7 @Controller
 8 public class TemplateController{
 9 
10     @RequestMapping("/test")
11     public String template(Model model) {
12         // 存储数据
13         model.addAttribute("msg", "Hello Thymeleaf!!!");
14         // 返回页面
15         return "template1";
16     }
17 }

Thymeleaf配置类ThymeleafProperties,之前我们SpringMVC阶段是默认在WEB-INF目录下找.jsp文件,现在是在templates目录下找.html文件

第三步:创建HTML文件测试,注意在没有引入Thymeleaf依赖之前是不能通过Controller控制器来访问templates目录里面的资源

 1 <!DOCTYPE html>
 2 
 3 <html lang="en" xmlns:th="http://www.thymeleaf.org">
 4 <head>
 5     <meta charset="UTF-8">
 6     <title>测试页面</title>
 7 </head>
 8 <body>
 9     <!--th:text就是将h1中的内容设置为它指定的值,和之前学习的Vue一样-->
10     <h1 th:text="${msg}"></h1>
11 </body>
12 </html>

第四步:启动服务器看前端浏览器访问结果

到此,我们的Thymeleaf模板引擎就介绍完毕了,谢谢大家的支持!!! 

posted @ 2021-04-11 14:13  没有你哪有我  阅读(404)  评论(0编辑  收藏  举报