Spring Boot Thymeleaf条件判断

      Thymeleaf中使用th:if和th:unless属性进行条件判断,标签只有在th:if中的条件成立时才显示,th:unless与th:if恰好相反,只有条件不成立时,才会显示其内容。

测试Thymeleaf条件判断

程序清单:/springboot2/src/main/java/com/dwx/hello/ThymeleafController.java

package com.dwx.hello;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.WebRequest;
@Controller
public class ThymeleafController {
	@RequestMapping("/ifTest")
	public String ifTest(WebRequest request) {
		request.setAttribute("userName", "jack", WebRequest.SCOPE_REQUEST);
		request.setAttribute("sex", "0", WebRequest.SCOPE_REQUEST);
		request.setAttribute("age", 22, WebRequest.SCOPE_REQUEST);
		return "success";
	}
}

程序清单:/springboot2/src/main/resources/templates/success.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>thymeleaf条件判断</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}">
<link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}"/>
<script type="text/javascript" th:src="@{js/jquery-1.11.0.min.js}"></script>
<script type="text/javascript" th:src="@{js/bootstrap.min.js}"></script>
</head>
<body>
	<div class="panel panel-primary">
		<div class="panel-heading">
			<h3 class="panel-title">thymeleaf条件判断</h3>
		</div>
	</div>
	<div class="container">
		<div class="row">
			<div class="col-md-4">
			<p>条件成立时显示</p>
			<p th:if="${userName!=null}">用户名:<span th:text="${userName}"></span></p>
			<p>条件不成立时显示</p>
			<p th:unless="${address!=null}"><span>地址为空!</span></p>
			<div class="col-md-4" th:switch="${sex}">
				<p th:case="0">男</p>
				<p th:case="1">女</p>
			</div>
			</div>
		</div>
	</div>
</body>
</html>

Spring Boot项目启动后,访问以下地址:http://localhost:8080/ifTest

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云淡风轻58

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值