08-Java框架-SpringBoot整合thymeleaf

SpringBoot整合thymeleaf,以及thymeleaf的相关介绍
摘要由CSDN通过智能技术生成

一、thymeleaf介绍

Thymeleaf 是新一代 Java 模板引擎,与 Velocity、FreeMarker 等传统 Java 模板引擎不同,Thymeleaf 支持 HTML 原型,其文件后缀为“.html”,因此它可以直接被浏览器打开,此时浏览器会忽略未定义的 Thymeleaf 标签属性,展示 thymeleaf 模板的静态页面效果;当通过 Web 应用程序访问时,Thymeleaf 会动态地替换掉静态内容,使页面动态显示。

Thymeleaf 通过在 html 标签中,增加额外属性来达到“模板+数据”的展示方式,示例代码如下。

<!DOCTYPE html>
<!--设置命名空间:th才能生效使用 -->
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!-- th:text 为Thymeleaf的属性,用于展示文本 -->
<h1 th:text="hello Thymeleaf">hello HTML</h1>
</body>
</html>

同时,Spring Boot 推荐使用 Thymeleaf 作为其模板引擎。SpringBoot 为 Thymeleaf 提供了一系列默认配置,项目中一但导入了 Thymeleaf 的依赖,相对应的自动配置 (ThymeleafAutoConfiguration) 就会自动生效,因此 Thymeleaf 可以与 Spring Boot 完美整合 。

二、SpringBoot整合thymeleaf

官网:https://www.thymeleaf.org/

2.1 导入依赖

构建springboot项目,导入依赖,创建启动类。

<!--引入父依赖-->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.10</version>
    <relativePath/> <!-- lookup parent from repository:当子项目中未定义版本号时可以从父项目中引用 -->
</parent>
...
<dependencies>
    <!--springbootweb依赖(包含:spring,springmvc,tomcat等依赖)-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--Thymeleaf 依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
</dependencies>

2.2 配置yml

application.yml

server:
  port: 80  #端口
#thymeleaf参数
spring:
  thymeleaf:
    prefix: classpath:/templates/ #视图前缀
    suffix: .html                 #视图后缀
    encoding: UTF-8               #编码
    cache: false                  #缓存(默认开启,开发时建议关闭)
# 以上关于thymeleaf的这些参数其实都无需设置,因为都默认设置好了。参考:ThymeleafProperties

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"
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值