SpringBoot 的Web 开发

本文介绍如何在SpringBoot项目中使用Thymeleaf模板引擎,并演示了基本的页面结构、如何在模板中访问和展示Model数据、迭代数据及进行条件判断等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. SpringBoot 的Thrmeleaf模板引擎
    Spring Boot中推荐使用Thrmeleaf作为模板引擎,因为Thrmeleaf 提供了完美的SpringMVC的支持。虽然Spring Boot 中还提供了其他的大量的模板,包括:Free Marker,Groovy,Velocity和Mustache

  2. Thrmeleaf 是一个Java类库,可以作为MVC的Web应用的View层

  3. Thrmeleaf 还提供了额外的模块与SpringMVC集成,所以我们可以使用Thrmeleaf 完全替代JSP

  4. 下面的代码是一个基本的Thrmeleaf 模板页面:

<!DOCTYPE html>
<html xmlns:th="http://www.thrmeleaf.org"><!-- 可以将静态页面转换成动态的视图,需要进行动态处理的元素将使用"th:"为前缀 -->
<head>
<meta charset="UTF-8">
<title>默认页面</title>
</head>
<body>
	
</body>
</html>
  1. 访问model中的数据
<div>
		<div>
			<h3>访问model</h3>
		</div>
		<div>
			<!-- 访问model中的singlePerson 的name属性,注意:需要处理的动态内容需要加上"th:"前缀 -->
			<span th:text="${singlePerson.name}"></span>
		</div>
	</div>
  1. model中的数据迭代:
<div>
		<div>
			<h3>列表</h3>
		</div>
		<div>
			<ul>
				<!-- 使用 th:each来做循环迭代,person作为迭代元素来使用,然后像访问model中的数据那一步一样来访问迭代元素的属性-->
				<li class="list-group-item" th:each="person:${people}">
					<span th:text="person.name"></span>
					<span th:text="person.age"></span>
				</li>
			</ul>
		</div>
	</div>

7.数据判断

<!-- 判断people是否为空,Thrmeleaf支持>、<、>=、<=、==、 !=作为比较条件,同时也支持将SpringEl表达式语言用于条件中  -->
	<div th:if="${not #list.isEmpty(people)}">
		<div>
			<div>
				<h3>列表</h3>
			</div>
			<div>
				<ul>
					<!-- 使用 th:each来做循环迭代,person作为迭代元素来使用,然后像访问model中的数据那一步一样来访问迭代元素的属性-->
					<li class="list-group-item" th:each="person:${people}">
						<span th:text="person.name"></span>
						<span th:text="person.age"></span>
					</li>
				</ul>
			</div>
		</div>
	</div>

8.在JavaScript中访问model

<script th:inline="javascript">
		var single = [${singlePerson}];
		console.log(single.name + "/" + single.age);
	</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值