前面介绍了Spring Boot的优势,而后介绍了如何快速建立Spring Boot 项目。不清楚的朋友能够看看以前的文章:https://www.cnblogs.com/zhangweizhong/category/1657780.html。html
今天咱们主要来看看 Thymeleaf 在 Spring Boot 中的整合!前端
这个系列课程的完整源码,也会提供给你们。你们关注个人微信公众号(架构师精进),回复:springboot源码 获取这个系列课程的完整源码。或者点此连接直接下载完整源码java
Spring Boot 2主要支持页面模板是 Thymeleaf 和 Freemarker ,固然,做为 Java 最最基本的页面模板 Jsp ,Spring Boot 也是支持的,只是使用比较麻烦。web
Thymeleaf 做为新一代 Java 模板引擎,它的功能与 Velocity、FreeMarker 等传统 Java 模板引擎比较相似,可是Thymeleaf 模板后缀为 .html
,能够直接被浏览器打开,所以,开发时很是方便。redis
它既可让前端工程师在浏览器中直接打开查看样式,也可让后端工程师结合真实数据查看显示效果,同时,SpringBoot 提供了 Thymeleaf 自动化配置解决方案,所以在 SpringBoot 中使用 Thymeleaf 很是方便。spring
事实上, Thymeleaf 除了展现基本的 HTML ,进行页面渲染以外,也能够做为一个 HTML 片断进行渲染,例如咱们在作邮件发送时,可使用 Thymeleaf 做为邮件发送模板。后端
新项目整合 Thymeleaf 很是容易,只须要建立项目时勾上 Thymeleaf 便可,这里就不说了。浏览器
下面说说怎么在现有的项目中手动整合Thymeleaf:缓存
一、在pom.xml 增长依赖以下:springboot
<!-- 引入 redis 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>1.5.7.RELEASE</version> </dependency>
二、application.properties 文件增长Thymeleaf 相关配置
############################################################ # # thymeleaf 模板 # ############################################################ spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.servlet.content-type=text/html # 关闭缓存 spring.thymeleaf.cache=false
spring.thymeleaf.prefix 指定模板页面的路径
三、增长前台页面
在resource\templates\thymeleaf 目录下增长index.html 页面
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
Thymeleaf模板引擎
<h1 th:text="${name}">hello Spring Boot~~~~~~~</h1>
</body>
</html>
th:text 就是Thymeleaf的标签,
用于处理标签体的文本内容。
其余更对的标签及用法,我会在下一篇文章中介绍。
四、建立 Controller
接下来咱们就能够建立 Controller 了,实际上引入 Thymeleaf 依赖以后,咱们能够不作任何配置。新建的ThymeleafController以下:
package com.weiz.controller; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import com.weiz.pojo.User; @Controller @RequestMapping("th") public class ThymeleafController { @RequestMapping("/index") public String index(ModelMap map) { map.addAttribute("name", "thymeleaf-index"); return "thymeleaf/index"; }
}
在ThymeleafController
中返回逻辑视图名,逻辑视图名为 index
,意思咱们须要在 resources/templates/t
目录下提供一个名为 hymeleaf
index.html
的 Thymeleaf
模板文件。
五、运行效果
在浏览器中输入:http://localhost:8080/th/index 查看页面返回结果。
主要向你们简单介绍了 Spring Boot 整合 Thymeleaf,仍是比较简单的。下一篇文章会给你们详细介绍Thymeleaf的经常使用标签和用法。你们也能够阅读 Thymeleaf 官方文档学习 Thymeleaf 的更多用法。
这个系列课程的完整源码,也会提供给你们。你们关注个人微信公众号(架构师精进),回复:springboot源码 获取这个系列课程的完整源码。