8.Thymeleaf

在之前的web项目中,我们的前端页面是用Jsp写的,但SpringBoot默认不支持Jsp,它推荐我们使用Thymeleaf模板引擎

和Jsp一样,我们可以写一个Thymeleaf页面模板,在模板里写上表达式,模板引擎就会通过这个模板和后台封装的数据把这表达式解析、填充到我们指定的位置,最后将数据展示出来

引入Thymeleaf的场景启动器

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

点进去发现这个启动器导入了下面几个依赖

<dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <version>2.6.2</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.thymeleaf</groupId>
      <artifactId>thymeleaf-spring5</artifactId>
      <version>3.0.14.RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.thymeleaf.extras</groupId>
      <artifactId>thymeleaf-extras-java8time</artifactId>
      <version>3.0.4.RELEASE</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>

我们来看一下Thymeleaf的自动配置规则,找到ThymeleafProperties,看到默认的前缀和后缀

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

public static final String DEFAULT_SUFFIX = ".html";

我们只需要把html页面放在类路径下的templates下,Thymeleaf就可以帮我们自动渲染了

TestController

@Controller
public class TestController {
    @RequestMapping("/t1")
    public String test1(Model model){
        model.addAttribute("msg","Hello SpringBoot");
        return "test";
    }
}

test.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div th:text="${msg}"></div>
</body>
</html>

关于Thymeleaf语法的学习还是要参考官方文档

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值