• 整合视图层(Thymeleaf的使用)


    Thymeleaf简介

    Thymeleaf的意思是模板引擎,适用于Web和独立环境,能够处理HTML,XML,JavaScript,CSS甚至纯文本,类似于Velocity,FreeMaker等传统的java模板引擎,但是与传统 Java 模板引擎不同的是,Thymeleaf 支持 HTML 原型.

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

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

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

    整合

    首先进行创建项目

    SpringBoot整合Thymeleaf非常容易,只需要在创建项目时加入Thymeleaf即可

    创建完成后,它的pom文件如下:

    当然,Thymeleaf不仅可以在SpringBoot当中使用,还可以用到其他地方,只是SpringBoot对于Thymeleaf提供了一整套的自动化配置方案, 这一套配置类的属性在org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties中,源码如下:

    1. package com.example.config;
    2. import org.springframework.boot.context.properties.ConfigurationProperties;
    3. import java.nio.charset.Charset;
    4. import java.nio.charset.StandardCharsets;
    5. @ConfigurationProperties(prefix = "spring.thymeleaf")
    6. public class ThymeleafProperties {
    7. private static final Charset DEFAULT_ENCODING =
    8. StandardCharsets.UTF_8;
    9. public static final String DEFAULT_PREFIX =
    10. "classpath:/templates/";
    11. public static final String DEFAULT_SUFFIX =
    12. ".html";
    13. private boolean checkTemplate = true;
    14. private boolean checkTemplateLocation = true;
    15. private String prefix = DEFAULT_PREFIX;
    16. private String suffix = DEFAULT_SUFFIX;
    17. private String mode = "HTML";
    18. private Charset encoding = DEFAULT_ENCODING;
    19. private boolean cache = true;
    20. }

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

    前三个static变量定义的是:默认编码格式;视图解析器前缀;后缀;

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

    这些配置如果自己提供,则在application.properties中以spring.thymeleaf为前缀开始进行相关配置,如果不自己提供,则使用默认的

    我们刚才提到的SpringBoot为Thymeleaf提供了自动化配置类,则是org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,源码如下:

    1. package com.example.config;
    2. import org.springframework.boot.autoconfigure.AutoConfigureAfter;
    3. import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
    4. import org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration;
    5. import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
    6. import org.springframework.boot.context.properties.EnableConfigurationProperties;
    7. import org.springframework.context.annotation.Configuration;
    8. import org.thymeleaf.spring5.SpringTemplateEngine;
    9. import org.thymeleaf.templatemode.TemplateMode;
    10. @Configuration
    11. @EnableConfigurationProperties(ThymeleafProperties.class)
    12. @ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
    13. @AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
    14. public class ThymeleafAutoConfiguration {
    15. }

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

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

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

    1. package com.example.controller;
    2. import com.example.pojo.User;
    3. import org.springframework.stereotype.Controller;
    4. import org.springframework.ui.Model;
    5. import org.springframework.web.bind.annotation.GetMapping;
    6. import java.util.ArrayList;
    7. import java.util.List;
    8. @Controller
    9. public class IndexController {
    10. @GetMapping("/index")
    11. public String index(Model model) {
    12. List<User> users = new ArrayList<>();
    13. for (int i = 0; i < 10; i++) {
    14. User u = new User();
    15. u.setId((long) i);
    16. u.setName("大黄:" + i);
    17. u.setAddress("济南:" + i);
    18. users.add(u);
    19. }
    20. model.addAttribute("users", users);
    21. return "index";
    22. }
    23. }
    24. @Data
    25. @Accessors(chain = true)
    26. public class User {
    27. private Long id;
    28. private String name;
    29. private String address;
    30. }

    在IndexController中返回逻辑视图名和数据,逻辑视图名为index,意思是我们需要在resources/templates目录下创建一个index.html的Thyleaf模板文件

    创建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接口,就能看到集合中的数据了

    另外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模板,一般在发送邮件时使用,例如我们在resources/templates目录下新建一个邮件模板mail.html,如下:

    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模板渲染成一个String字符串,再把这个字符串通过邮件的方式发送出去,那么该如何进行手动渲染呢?

    1. package com.example;
    2. import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;
    3. import org.junit.jupiter.api.Test;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.boot.test.context.SpringBootTest;
    6. import org.thymeleaf.TemplateEngine;
    7. import org.thymeleaf.context.Context;
    8. @SpringBootTest
    9. class mail {
    10. @Autowired
    11. TemplateEngine templateEngine;
    12. @Test
    13. void test1(){
    14. Context context = new Context();
    15. context.setVariable("username", "javaboy");
    16. context.setVariable("position", "Java工程师");
    17. context.setVariable("salary", 99999);
    18. String mail = templateEngine.process("mail", context);
    19. System.out.println(mail);
    20. }
    21. }

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

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

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

    以上内容就是Spring Boot整合Thymeleaf的几个关键点,希望能够帮助到大家

  • 相关阅读:
    21、Flink 的table API与DataStream API 集成(1)- 介绍及入门示例、集成说明
    第二章Maven的使用
    基于Java毕业设计长鸟交易市场信息平台源码+系统+mysql+lw文档+部署软件
    快速入门:构建您的第一个 .NET Aspire 应用程序
    利用噪声构建美妙的 CSS 图形
    Redis企业版—比Redis开源更好用!
    MATLAB--微分方程
    英伟达与斯坦福携手,打造未来全息XR眼镜:头带时代的终结
    美国市场三星手机超苹果 中国第一属华为
    JVM(Java虚拟机模型、Java运行时数据区模型)
  • 原文地址:https://blog.csdn.net/LKS_010620/article/details/125466037