javascript
SpringBoot中使用Thymeleaf常用功能(二):测试Thymeleaf条件判断
環(huán)境搭建請先閱讀文章一
在一的基礎(chǔ)上
先在index.html中添加超鏈接
<a th:href="@{iftest}">測試條件判斷</a>
在ThymeleafController.java中新增iftest:
/*
* 保存數(shù)據(jù)到作用范圍域,用于測試Thymeleaf的條件判斷
* */
@RequestMapping("/iftest")
public String iftest(WebRequest webRequest){
// 保存數(shù)據(jù)到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方法用來響應(yīng)第二個請求:<a th:href="@{iftest}">測試條件判斷</a>
在此方法中分別設(shè)置了username、age、role三個變到request作用域中,然后返回success2.html,保存數(shù)據(jù)到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 面板標(biāo)題。 -->
<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中條件成立時才顯示結(jié)果</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恰好相反,只有表達式中的條件不成立,才會顯示結(jié)果</font></p><br/>
<span th:unless="${address != null}">address為空</span><br/>
<p><font color="red">支持多路選擇Switch結(jié)構(gòu),默認屬性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>
運行結(jié)果:
總結(jié)
以上是生活随笔為你收集整理的SpringBoot中使用Thymeleaf常用功能(二):测试Thymeleaf条件判断的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringBoot中使用Thymele
- 下一篇: SpringBoot使用thymelea