环境搭建请先阅读文章一
在一的基础上
先在index.html中添加超链接
<a th:href="@{iftest}">测试条件判断</a>
在ThymeleafController.java中新增iftest:
附:
/*
* 保存数据到作用范围域,用于测试Thymeleaf的条件判断
* */
@RequestMapping("/iftest")
public String iftest(WebRequest webRequest){
// 保存数据到request作用范围域,Spring MVC更推荐使用WebRequest
webRequest.setAttribute("username", "badao", RequestAttributes.SCOPE_REQUEST);
webRequest.setAttribute("age", 22, RequestAttributes.SCOPE_REQUEST);
webRequest.setAttribute("role", "admin", RequestAttributes.SCOPE_REQUEST);
return "success2"; }
iftest方法用来响应第二个请求:<a th:href="@{iftest}">测试条件判断</a>
在此方法中分别设置了username、age、role三个变到request作用域中,然后返回success2.html,保存数据到request作用范围域,Spring MVC更推荐使用WebRequest。
success2.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
<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">
<!-- .panel-heading 面板头信息。 -->
<div class="panel-heading">
<!-- .panel-title 面板标题。 -->
<h3 class="panel-title">Thymeleaf条件判断</h3>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-4">
<p><font color="red">th:if中条件成立时才显示结果</font></p><br/>
<span th:if="${username != null}">username不为空</span><br/>
<span th:if="${age != null}">age不为空</span><br/>
<p><font color="red">th:unless与th:if恰好相反,只有表达式中的条件不成立,才会显示结果</font></p><br/>
<span th:unless="${address != null}">address为空</span><br/>
<p><font color="red">支持多路选择Switch结构,默认属性default可以用*表示</font></p><br/>
<div th:switch="${role}">
<p th:case="'admin'">管理员</p>
<p th:case="'guest'">来宾</p>
<p th:case="*">其他</p>
</div>
</div>
</div>
</div>
</body>
</html>
运行结果: