SpringBoot web开发-12-springboot整合thymeleaf模板引擎

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

  • 第一步:引入thymeleaf,怎么引入呢,对于springboot来说,什么事情不都是一个start,我们去在项目中引入一下。给大家三个网址:

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

  • 导入thymeleaf启动器

<!--thymeleaf基于3.x开发-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  • 自动配置,ctrl+单击点击spring-boot-starter-thymeleaf查看具体依赖项
<dependency>
  <groupId>org.thymeleaf</groupId>
  <artifactId>thymeleaf-spring5</artifactId>
  <version>3.0.15.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>
  • 使用Thymeleaf:创建模板文件,并放在在指定resources目录下
  • 前面呢,我们已经入了Thymeleaf,那这个要怎么使用呢?我们首先得按照Spring Boot的自动配置原理看一下我们这个Thymeleaf的自动配置规侧,在按照那个规则,我们进行使用。我们去找一下Thymeleaf的自动配置类;

templates目录下的所有页面,只能通过controller来跳转!这个需要板引擎的支持!thymeLeaf,浏览器无法直接访问页面。resources目录下除了templates文件,其他目录下的资源都可以通过浏览器访问

  • 结论:需要使用thymeleaf,只需要导入对应的依赖3.0以上就可以了!我们将html放在我们的templates目录下即可:Thymeleaf 就能自动进行渲染。

与 Spring Boot 其他自定义配置一样,我们可以在 application.properties/yml 中修改以 spring.thymeleaf 开始的属性,以实现修改 Spring Boot 对 Thymeleaf 的自动配置的目的。

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

public static final String DEFAULT_SUFFIX = ".html";
  • 后台数据发送
@Controller
public class TestController {
    @RequestMapping("/test")
    public String test(Model model){
        model.addAttribute("msg","hello springboot!");
        return "test";
    }
}
  • 前端模板设置xmlns:th="http://www.thymeleaf.org"命名空间定义
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--所有的htmL元素都可以被thymeLeaf替换接管:th:元素名-->
<p th:text="${msg}"></p>
</body>
</html>
  • 启动程序,在浏览器访问访问http://127.0.0.1:8080/test进行测试。
  • 经过上述步骤:springboot整合thymeleaf就简单的实现了,省去了在springmvc阶段大量的配置过程。
下一篇:SpringBoot-13-mvc配置原理
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值