SpringBoot之Thymeleaf整合

前言

Thymeleaf 简介

Thymeleaf 是新一代 Java 模板引擎,它类似于 Velocity、FreeMarker 等传统 Java 模板引擎,但是与传统 Java 模板引擎不同的是,Thymeleaf 支持 HTML 原型。Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式。Thymeleaf 除了展示基本的 HTML ,进行页面渲染之外,也可以作为一个 HTML 片段进行渲染。Thymeleaf 模板后缀为 .html,可以直接被浏览器打开,因此,预览时非常方便。


下面,我们来学习一下Thymeleaf。

正文

首先,项目是以SpringBoot为基础的:

  • 加入pom.xml 依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  • 创建controller层
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.zys.thymeleaf.pojo.User;

import java.util.ArrayList;
import java.util.List;

@Controller
public class UserController {
    @GetMapping("/user")
    public String user(Model model) {
        List<User> users = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            User u = new User();
            u.setId((long) i);
            u.setName("boy:" + i);
            u.setAddress("北京:" + i);
            users.add(u);
        }
        model.addAttribute("users", users);
        return "user";
    }
}

在 UserController 中返回逻辑视图名+数据,逻辑视图名为 index。

  • 创建 Thymeleaf
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>User</title>
</head>
<body>
<table border="1">
    <tr>
        <td>编号</td>
        <td>用户名</td>
        <td>地址</td>
    </tr>
    <tr th:each="user : ${users}">
        <td th:text="${user.id}"></td>
        <td th:text="${user.name}"></td>
        <td th:text="${user.address}"></td>
    </tr>
</table>
</body>
</html>

user.html 上面要引入 thymeleaf 名称空间。通过 th:each 指令来遍历一个集合,数据的展示通过 th:text 指令来实现。
配置完成后,启动项目,访问localhost:8080/user接口,就能看到集合中的数据啦:

编号-用户名-地址
0 -----boy:0--北京:0
1 -----boy:1--北京:1
2 -----boy:2--北京:2
3 -----boy:3--北京:3
4 -----boy:4--北京:4
5 -----boy:5--北京:5
6 -----boy:6--北京:6
7 -----boy:7--北京:7
8 -----boy:8--北京:8
9 -----boy:9--北京:9

探索thymeleaf部分源码

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

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
        private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
        public static final String DEFAULT_PREFIX = "classpath:/templates/";
        public static final String DEFAULT_SUFFIX = ".html";
        private boolean checkTemplate = true;
        private boolean checkTemplateLocation = true;
        private String prefix = DEFAULT_PREFIX;
        private String suffix = DEFAULT_SUFFIX;
        private String mode = "HTML";
        private Charset encoding = DEFAULT_ENCODING;
        private boolean cache = true;
        //...
}
  • 首先通过 @ConfigurationProperties 注解,将 application.properties 前缀为 spring.thymeleaf 的配置和这个类中的属性绑定。
  • 前三个 static 变量定义了默认的编码格式、视图解析器的前缀、后缀等。
  • 从前三行配置中,可以看出来,Thymeleaf 模板的默认位置在 resources/templates 目录下,默认的后缀是 html 。
  • 这些配置,如果开发者不自己提供,则使用 默认的,如果自己提供,则在 application.properties 中以 spring.thymeleaf 开始相关的配置。
    而我们刚刚提到的,SpringBoot 为 Thymeleaf 提供的自动化配置类,则是org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration ,部分源码如下:
@Configuration
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration {
}

可以看到,在这个自动化配置类中,首先导入 ThymeleafProperties ,然后 @ConditionalOnClass 注解表示当当前系统中存在 TemplateMode 和 SpringTemplateEngine 类时,当前的自动化配置类才会生效,即只要项目中引入了 Thymeleaf 相关的依赖,这个配置就会生效。
这些默认的配置我们几乎不需要做任何更改就可以直接使用。如果开发者有特殊需求,则可以在 application.properties 中配置以 spring.thymeleaf 开头的属性即可。

总结

本文章学习了SpringBoot整合Thymeleaf,文章中例子是比较简单的。如需更多的复杂操作,可参考官网。关于 Thymeleaf 这个页面模板本身更多的用法,大家可以参考 Thymeleaf 的文档:https://www.thymeleaf.org。再次感谢江南一点雨的文章。我的这些SpringBoot文章,只是对自己的沉淀和分享,如侵权可与我联系。

一寸光阴一寸金

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容