springboot入门教程(2)_Thymeleaf集成

时间:2022-05-04
本文章向大家介绍springboot入门教程(2)_Thymeleaf集成,主要内容包括1)、引入Thymeleaf包、2)、模板解析器配置、3)、准备后台数据、4)、编写模板userList.html、5)、运行Application,运行项目、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。
springboot入门教程_Thymeleaf集成

摘要: 上一篇我们搭建了一个简单的demo,这篇我们来介绍下基于spring boot的web开发的入门内容:Thymeleaf模板、web相关配置、tomcat相关设置等

该篇主要介绍下springboot 和Thymeleaf集成(不具体介绍Thymeleaf语法--关于Thymeleaf语法将单独进行介绍)

1)、引入Thymeleaf包

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

2)、模板解析器配置

spring-boot很多配置都有默认配置,比如默认页面映射路径为 classpath:/templates/*.html 同样静态文件路径为 classpath:/static/

在application.properties中可以配置thymeleaf模板解析器属性.就像使用springMVC的JSP解析器配置一样

  • 具体可以配置的参数可以查看
  • org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties这个类,上面的配置实际上就是注入到该类中的属性值.

3)、准备后台数据

编写一个conntroller提供测试数据(这里牵涉到一点和spring mvc相关的内容,我们后面再介绍,先忽略),代码如下

代码解释:提供一个userList方法返回的model中包含一个user数组和count,user是一个普通的实体类,里面有id,age,name三个属性。  方法是完全spring MVC的内容(如果不熟的朋友请先熟悉下再看后续文章)

4)、编写模板userList.html

放到src/main/resources/templates目录下,这是spring boot和Thymeleaf集成的默认配置路径

5)、运行Application,运行项目

访问http://localhost:8080/user/userList,即可看到模板获取到后台数据后渲染到页面。

好了,这篇就先到这里,敬请期待下一篇:springboot 入门教程-的运行原理,关键注解和配置。