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

在人生的道路上,不管是潇洒走一回,或者是千山独行,皆须是自己想走的路,虽然,有的人并不是很快就能找到自己的方向和道路,不过,只要坚持到底,我相信,就一定可以找到自己的路,只要找到路,就不必怕路途遥远了。

导读:本篇文章讲解 SpringBoot web开发-12-springboot整合thymeleaf模板引擎,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

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配置原理

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/123859.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!