极简 Spring Boot 整合 Thymeleaf 页面模板

2年前 (2022) 程序员胖胖胖虎阿
220 0 0
极简 Spring Boot 整合 Thymeleaf 页面模板
点击
“牧码小子”关注,和众多大牛一起成长!

关注后,后台回复 java ,领取松哥为你精心准备的技术干货!



虽然现在慢慢在流行前后端分离开发,但是据松哥所了解到的,还是有一些公司在做前后端不分的开发,而在前后端不分的开发中,我们就会需要后端页面模板(实际上,即使前后端分离,也会在一些场景下需要使用页面模板,例如邮件发送模板)。

早期的 Spring Boot 中还支持使用 Velocity 作为页面模板,现在的 Spring Boot 中已经不支持 Velocity 了,页面模板主要支持 Thymeleaf 和 Freemarker ,当然,作为 Java 最最基本的页面模板 Jsp ,Spring Boot 也是支持的,只是使用比较麻烦。

松哥打算用三篇文章分别向大家介绍一下这三种页面模板技术。

今天我们主要来看看 Thymeleaf 在 Spring Boot 中的整合!

Thymeleaf 简介

Thymeleaf 是新一代 Java 模板引擎,它类似于 Velocity、FreeMarker 等传统 Java 模板引擎,但是与传统 Java 模板引擎不同的是,Thymeleaf 支持 HTML 原型。

它既可以让前端工程师在浏览器中直接打开查看样式,也可以让后端工程师结合真实数据查看显示效果,同时,SpringBoot 提供了 Thymeleaf 自动化配置解决方案,因此在 SpringBoot 中使用 Thymeleaf 非常方便。

事实上, Thymeleaf 除了展示基本的 HTML ,进行页面渲染之外,也可以作为一个 HTML 片段进行渲染,例如我们在做邮件发送时,可以使用 Thymeleaf 作为邮件发送模板。

另外,由于 Thymeleaf 模板后缀为 .html,可以直接被浏览器打开,因此,预览时非常方便。

整合

  • 创建项目

Spring Boot 中整合 Thymeleaf 非常容易,只需要创建项目时添加 Thymeleaf 即可:

极简 Spring Boot 整合 Thymeleaf 页面模板

创建完成后,pom.xml 依赖如下:

  
  
  
  1. <dependency>

  2. <groupId>org.springframework.boot</groupId>

  3. <artifactId>spring-boot-starter-thymeleaf</artifactId>

  4. </dependency>

  5. <dependency>

  6. <groupId>org.springframework.boot</groupId>

  7. <artifactId>spring-boot-starter-web</artifactId>

  8. </dependency>

当然,Thymeleaf 不仅仅能在 Spring Boot 中使用,也可以使用在其他地方,只不过 Spring Boot 针对 Thymeleaf 提供了一整套的自动化配置方案,这一套配置类的属性在 org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties 中,部分源码如下:

  
  
  
  1. @ConfigurationProperties(prefix = "spring.thymeleaf")

  2. public class ThymeleafProperties {

  3. private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;

  4. public static final String DEFAULT_PREFIX = "classpath:/templates/";

  5. public static final String DEFAULT_SUFFIX = ".html";

  6. private boolean checkTemplate = true;

  7. private boolean checkTemplateLocation = true;

  8. private String prefix = DEFAULT_PREFIX;

  9. private String suffix = DEFAULT_SUFFIX;

  10. private String mode = "HTML";

  11. private Charset encoding = DEFAULT_ENCODING;

  12. private boolean cache = true;

  13. //...

  14. }

  1. 首先通过 @ConfigurationProperties 注解,将 application.properties 前缀为 spring.thymeleaf 的配置和这个类中的属性绑定。

  2. 前三个 static 变量定义了默认的编码格式、视图解析器的前缀、后缀等。

  3. 从前三行配置中,可以看出来, Thymeleaf 模板的默认位置在 resources/templates 目录下,默认的后缀是 html 。

  4. 这些配置,如果开发者不自己提供,则使用 默认的,如果自己提供,则在 application.properties 中以 spring.thymeleaf 开始相关的配置。

而我们刚刚提到的,Spring Boot 为 Thymeleaf 提供的自动化配置类,则是 org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration ,部分源码如下:

  
  
  
  1. @Configuration

  2. @EnableConfigurationProperties(ThymeleafProperties.class)

  3. @ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })

  4. @AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })

  5. public class ThymeleafAutoConfiguration {

  6. }

可以看到,在这个自动化配置类中,首先导入 ThymeleafProperties ,然后 @ConditionalOnClass 注解表示当当前系统中存在 TemplateModeSpringTemplateEngine 类时,当前的自动化配置类才会生效,即只要项目中引入了 Thymeleaf 相关的依赖,这个配置就会生效。

这些默认的配置我们几乎不需要做任何更改就可以直接使用了。如果开发者有特殊需求,则可以在 application.properties 中配置以 spring.thymeleaf 开头的属性即可。

  • 创建 Controller

接下来我们就可以创建 Controller 了,实际上引入 Thymeleaf 依赖之后,我们可以不做任何配置。新建的 IndexController 如下:

  
  
  
  1. @Controller

  2. public class IndexController {

  3. @GetMapping("/index")

  4. public String index(Model model) {

  5. List<User> users = new ArrayList<>();

  6. for (int i = 0; i < 10; i++) {

  7. User u = new User();

  8. u.setId((long) i);

  9. u.setName("javaboy:" + i);

  10. u.setAddress("深圳:" + i);

  11. users.add(u);

  12. }

  13. model.addAttribute("users", users);

  14. return "index";

  15. }

  16. }

  17. public class User {

  18. private Long id;

  19. private String name;

  20. private String address;

  21. //省略 getter/setter

  22. }

IndexController 中返回逻辑视图名+数据,逻辑视图名为 index ,意思我们需要在 resources/templates 目录下提供一个名为 index.htmlThymeleaf 模板文件。

  • 创建 Thymeleaf

  
  
  
  1. <!DOCTYPE html>

  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">

  3. <head>

  4. <meta charset="UTF-8">

  5. <title>Title</title>

  6. </head>

  7. <body>

  8. <table border="1">

  9. <tr>

  10. <td>编号</td>

  11. <td>用户名</td>

  12. <td>地址</td>

  13. </tr>

  14. <tr th:each="user : ${users}">

  15. <td th:text="${user.id}"></td>

  16. <td th:text="${user.name}"></td>

  17. <td th:text="${user.address}"></td>

  18. </tr>

  19. </table>

  20. </body>

  21. </html>

Thymeleaf 中,通过 th:each 指令来遍历一个集合,数据的展示通过 th:text 指令来实现,

注意 index.html 最上面要引入 thymeleaf 名称空间。

配置完成后,就可以启动项目了,访问 /index 接口,就能看到集合中的数据了:

极简 Spring Boot 整合 Thymeleaf 页面模板

另外, Thymeleaf 支持在 js 中直接获取 Model 中的变量。例如,在 IndexController 中有一个变量 username

  
  
  
  1. @Controller

  2. public class IndexController {

  3. @GetMapping("/index")

  4. public String index(Model model) {

  5. model.addAttribute("username", "李四");

  6. return "index";

  7. }

  8. }

在页面模板中,可以直接在 js 中获取到这个变量:

  
  
  
  1. <script th:inline="javascript">

  2. var username = [[${username}]];

  3. console.log(username)

  4. </script>

这个功能算是 Thymeleaf 的特色之一吧。

手动渲染

前面我们说的是返回一个 Thymeleaf 模板,我们也可以手动渲染 Thymeleaf 模板,这个一般在邮件发送时候有用,例如我在 resources/templates 目录下新建一个邮件模板,如下:

  
  
  
  1. <!DOCTYPE html>

  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">

  3. <head>

  4. <meta charset="UTF-8">

  5. <title>Title</title>

  6. </head>

  7. <body>

  8. <p>hello 欢迎 <span th:text="${username}"></span>加入 XXX 集团,您的入职信息如下:</p>

  9. <table border="1">

  10. <tr>

  11. <td>职位</td>

  12. <td th:text="${position}"></td>

  13. </tr>

  14. <tr>

  15. <td>薪水</td>

  16. <td th:text="${salary}"></td>

  17. </tr>

  18. </table>

  19. <img src="http://www.javaboy.org/images/sb/javaboy.jpg" alt="">

  20. </body>

  21. </html>

这一个 HTML 模板中,有几个变量,我们要将这个 HTML 模板渲染成一个 String 字符串,再把这个字符串通过邮件发送出去,那么如何手动渲染呢?

  
  
  
  1. @Autowired

  2. TemplateEngine templateEngine;

  3. @Test

  4. public void test1() throws MessagingException {

  5. Context context = new Context();

  6. context.setVariable("username", "javaboy");

  7. context.setVariable("position", "Java工程师");

  8. context.setVariable("salary", 99999);

  9. String mail = templateEngine.process("mail", context);

  10. //省略邮件发送

  11. }

  1. 渲染时,我们需要首先注入一个 TemplateEngine 对象,这个对象就是在 Thymeleaf 的自动化配置类中配置的(即当我们引入 Thymeleaf 的依赖之后,这个实例就有了)。

  2. 然后构造一个 Context 对象用来存放变量。

  3. 调用 process 方法进行渲染,该方法的返回值就是渲染后的 HTML 字符串,然后我们将这个字符串发送出去。

这是 Spring Boot 整合 Thymeleaf 的几个关键点,关于 Thymeleaf 这个页面模板本身更多的用法,大家可以参考 Thymeleaf 的文档:https://www.thymeleaf.org。

总结

本文主要向大家简单介绍了 Spring Boot 和 Thymeleaf 整合时的几个问题,还是比较简单的,大家可以阅读 Thymeleaf 官方文档学习 Thymeleaf 的更多用法。本文案例我已上传到 GitHub ,欢迎大家 star :https://github.com/lenve/javaboy-code-samples

关于本文,有问题欢迎留言讨论。

极简 Spring Boot 整合 Thymeleaf 页面模板

●另一种缓存,Spring Boot 整合 Ehcache

●Spring Boot 整合 Shiro ,两种方式全总结!

●Docker 入门及安装[Docker 系列-1]

●Spring Boot 中 10 行代码构建 RESTful 风格应用

●Nginx 极简入门教程!

●Spring Boot 一个依赖搞定 session 共享,没有比这更简单的方案了!

●Spring Boot 操作 Redis,三种方案全解析!

●面试干货 | Java 能否自定义一个类叫 java.lang.System?

●这一次,我连 web.xml 都不要了,纯 Java 搭建 SSM 环境

●没有一条路是容易的,特别是转行计算机这条路

极简 Spring Boot 整合 Thymeleaf 页面模板

极简 Spring Boot 整合 Thymeleaf 页面模板
你点的每个赞,我都认真当成了喜欢

本文分享自微信公众号 - 江南一点雨(a_javaboy)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

版权声明:程序员胖胖胖虎阿 发表于 2022年11月10日 上午6:48。
转载请注明:极简 Spring Boot 整合 Thymeleaf 页面模板 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...