thymeleaf模板引擎


前言

Thymeleaf是Spring Boot官方的推荐使用模板。

所以放弃jsp吧(我不是打广告的)


一、thymeleaf是什么?

Thymeleaf是一个用于Web和独立Java环境的模板引擎,能够处理HTML、XML、JavaScript、CSS甚至纯文本。能轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用.

Thymeleaf 3.0是一个完全彻底重构的模板引擎,极大的减少内存占用和提升性能和并发性,避免v2.1版因大量的输出标记的集合产生的资源占用。

Thymeleaf 3.0放弃了大多数面向DOM的处理机制,变成了一个基于事件的模板处理器,它通过处理模板标记或文本并立即生成其输出,甚至在新事件之前响应模板解析器/缓存事件。

二、使用步骤

1.导入坐标

<!--        引入thymeleaf模板引擎-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

更改SpringBoot默认版本

 	<properties>
        <java.version>1.8</java.version>
        <thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
        <--布局功能支持的程序 thymeleaf3版本 对应 layout2以上版本-->
        <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
    </properties>

2.Spring Boot项目中创建controller

@Controller
public class HelloController {

  
    @RequestMapping("/success")
    public String success(){

        return "success";
    }
}

在这里插入图片描述

3.分析源码

打开org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties

源码如下所示
在这里插入图片描述

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

这两行类似于SpringMVC框架里配置的视图解析器
在这里插入图片描述

4.配置success.html

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

5.启动主配置文件访问http://localhost:8080/success

在这里插入图片描述


总结

只要将html页面放到classpath:/templates/下,thmeleaf就能帮我们自动渲染了

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Thecoastlines

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值