SpringBoot实战教程(3)| 整合Thymeleaf
Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全代替传统JSP 。
目录
一、初始化SpringBoot项目
二、引入依赖pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
因为模板引擎要依赖于web模块,所以同时要将 spring-boot-starter-web 同时加入。
三、application.properties配置文件
# 默认端口
server.port=80
##### Thymeleaf配置 #####
# 默认编码
spring.thymeleaf.encoding=utf-8
# HTML5规范
spring.thymeleaf.mode=HTML5
# 默认放置目录
spring.thymeleaf.prefix=classpath:/templates/
# 模板后缀格式
spring.thymeleaf.suffix=.html
# 开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false
四、编写Controller类
IndexController.java
package com.csdn.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/hello")
public class IndexController {
@RequestMapping("/thymeleaf")
public String hello(ModelMap mmp) {
// 字符串
String str = "Thymeleaf";
mmp.put("str", str);
// 数组
List<Integer> arr = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
mmp.put("arr", arr);
// map集合
Map<String,Object> map = new HashMap<>();
map.put("name","张三");
map.put("age","28");
map.put("sex","男");
mmp.addAttribute("map",map);
return "hello";
}
}
五、编写html模板
hello.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>springboot-thymeleaf demo</title>
</head>
<body>
<p>显示字符串</p>
<div th:text="${str}" ></div>
<p>遍历数组方法一</p>
<div th:each="name:${arr}">[[${name}]]</div>
<p>遍历数组方法二</p>
<div th:each="name:${arr}" th:text="${name}"></div>
<p>遍历map</p>
<table class="layui-table" border="1">
<tr th:each="item,userStat:${map}">
<td th:text="${userStat.index}+1"></td>
<td th:text="${userStat.current.key}"></td><!-- key-->
<td th:text="${userStat.current.value}"></td><!-- value-->
</tr>
</table>
</body>
</html>
六、运行结果展示
作者:YangRoc
出处:https://www.cnblogs.com/YangRoc/p/17186453.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
如果本篇文章有帮助到你,你可以请作者喝杯咖啡表示鼓励 ☕️
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!