SpringBoot学习 — Thymeleaf 模板引擎

目录

了解

模板引擎的作用

SpringBoot整合Thymeleaf

Thymeleaf 语法 


了解

SpringBoot项目默认是不支持jsp的,如果我们直接使用纯静态页面的方式,会很麻烦,所以 SpringBoot 推荐我们使用模板引擎。

  • Thymeleaf 是用来开发Web 和独立环境项目的服务器端的Java模板引擎。
  • Spring官网支持的服务的渲染模板中,并不包含jsp,而是Thymeleaf 和Freemarker 等。
  • Thymeleaf 与SpringMVC 的视图技术及 SpringBoot 的自动装配集成的非常完美,几乎没有任何成本,只需我们关注Thymeleaf的语法即可。

模板引擎的作用

简单来说,我们写一个页面模板,比如有些动态值,我们可以写表达式。而这些动态的值,就是我们在后台封装的一些数据。然后把这个模板和这些数据交给模板引擎,模板引擎按照 这些数据,帮我们把表达式解析、填充到我们指定的位置,然后把数据最终生成一个我们想要的内容写出去。

SpringBoot整合Thymeleaf

 引入Thymeleaf

我们创建一个SpringBoot项目,添加相关依赖。

Spring官方文档

<!--    thymeleaf    -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>

Thymeleaf 分析

查看Thymeleaf的自动配置类 ThymeleafProperties :

@ConfigurationProperties(
    prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    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 = "classpath:/templates/";
    private String suffix = ".html";
    private String mode = "HTML";
    ...
}

自动配置 自动给我们默认分配了模板的前缀和后缀,我们只需要按部就班的将模板丢进去即可。

也就是将我们的html页面放在类路径下的templates 下,thymeleaf就会帮我们自动渲染。

测试

1.TestController

@Controller
public class TestController {

    @RequestMapping("/test")
    public String test(){
        return "test";
    }
}

2.测试页面 test.heml 放在templates 目录下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>wudimin</title>
</head>
<body>
<h1>Thymeleaf 测试成功</h1>
</body>
</html>

3.启动项目

 

Thymeleaf 语法 

Thymeleaf 官网  下载官方文档,需要使用时,根据官方文档查询。

学习的过程中发现一篇关于Thymeleaf 语法的不错的博客,可以多读读熟悉熟悉 Thymeleaf语法使用。

中文参考书册

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值