springboot+thymeleaf初步使用记录

前两天写了个评论模块,然后用到了thymeleaf模板,就在此记录下

项目地址

1.pom.xml添加依赖

<!-- 模板引擎 Thymeleaf 依赖 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 模板引擎 Thymeleaf  layout 依赖 -->
<dependency>
	<groupId>nz.net.ultraq.thymeleaf</groupId>
	<artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>
  1. 代码相关

项目目录 - 主要看/resource/templates就可以了,我的代码都是建立在此目录上的

springboot+thymeleaf初步使用记录

控制器处注解要用@Controller,不要用@RestController.

ModelMap继承LinkedHashMap,spring框架自动创建实例并作为controller的入参,下面是我的IndexController代码,主要就是构造页面数据。
springboot+thymeleaf初步使用记录

下面是user.html部分代码,主要是遍历用户数据展示
springboot+thymeleaf初步使用记录

thymeleaf模板还有许多其他有用的语法,我在这里写下几个,大家有需要再去找自己需要的。

属性 描述 示例
th:text 计算其值表达式并将结果设置为标签的标签体 <p th:text="${info}">java</p>,值为 null为空时,整个标签不显示任何内容。若有值,则显示其值
th:utext 和th:text基本一致,但是其会转义 如<h1>java</h1>;,th:text会输出完整内容,th:utext转义之后,会输出h1格式的

java

th:fragment 定义模板片段 layout页面常用&#60;div layout:fragment=“content” class=“table”>
th:if 条件为 true 时,显示模板⽚段,否则不显示 <p th:if="${show}">展示内容</p>
  1. form表单提交
    我们在实际应用中,会用到提交表单数据,下面是代码

IndexController.class

调用页面时,需要传入userEntity属性,否则页面展示会报错的,因为找不到这个属性。

springboot+thymeleaf初步使用记录

user.html
springboot+thymeleaf初步使用记录

写法有两种页面中都有体现,代码地址最后有。

UserEntity.class
springboot+thymeleaf初步使用记录

后台的接口
springboot+thymeleaf初步使用记录

这里需要注意的就是,页面中属性名称要和javaBean中一致,否则后台接收不到预期数据

  1. layout页面
    我们的应用页面,通常头尾部都是固定的,所以用layout来做分离。

IndexController.class
接到请求,去调用相应的模板
springboot+thymeleaf初步使用记录
index.html
图中标记的地方,一定要注意。依赖的模板一定要写进去。目录不要错。

springboot+thymeleaf初步使用记录

base.html
springboot+thymeleaf初步使用记录
最后的展现形式

springboot+thymeleaf初步使用记录

  1. 代码地址
    项目地址 我说的如果不明白,就去把代码拉下来,跑一下就都明白了

如果感觉这篇文章对你有帮助,点个赞,谢谢。
个人博客地址