Java 如何使用jstl检查列表是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20845554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if list is empty using jstl
提问by user3014926
I have defined a list collection in my servlet as following:
我在我的 servlet 中定义了一个列表集合,如下所示:
List<BookingRecord> list = getLast24();
req.setAttribute("records", list);
Then in JSP, I want to do following algorithm using jstl. If list is not empty, do XXXX, otherwise do YYYY.
然后在 JSP 中,我想使用 jstl 执行以下算法。如果列表不为空,则执行 XXXX,否则执行 YYYY。
I did something like this:
我做了这样的事情:
<c:when test="${not empty records}">
<table border="1">
<tbody>
<tr>
<th>id</th>
<th>hotel</th>
<th>room</th>
<th>guest id</th>
<th>start date</th>
<th>end date</th>
<th></th>
</tr>
<c:forEach items="${records}" var="record">
<tr<c:if test="${record.endDate != null }"> style="background-color: gainsboro"</c:if>>
<td>${record.id}</td>
<td>${record.hotelName}</td>
<td>${record.roomNumber}</td>
<td>${record.personId}</td>
<td><fmt:formatDate value="${record.startDate}" pattern="yyyy-MM-dd HH:mm"/></td>
<td><fmt:formatDate value="${record.endDate}" pattern="yyyy-MM-dd HH:mm"/></td>
<td>
<c:if test="${record.endDate == null }">
<form action="checkout" method="post">
<input type="hidden" name="recordId" value="${record.id}"/>
<input type="submit" value="退房"/>
</form>
</c:if>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</c:when>
<c:otherwise>
<h1>目前24小时内,没有订房</h1>
</c:otherwise>
But the tomcat gave me exception at
但是tomcat给了我例外
<c:when test="${not empty records}">
I appreciate if someone could help me out.
如果有人可以帮助我,我很感激。
回答by Anthony Lo
Replace the when in your jstl tag to if.
将 jstl 标记中的 when 替换为 if。
<c:if test="${not empty records}">
<c:if test="${not empty records}">
回答by M4ver1k
Please see the syntax for choose which is like a switch case or use if you want if statement
请参阅选择的语法,这类似于 switch case 或如果需要 if 语句,请使用
<c:choose>
<c:when test="${salary <= 0}">
Salary is very low to survive.
</c:when>
<c:when test="${salary > 1000}">
Salary is very good.
</c:when>
<c:otherwise>
No comment sir...
</c:otherwise>
</c:choose>
Also please refer thisfor jstl tags:
也请参考这里的 jstl 标签:
回答by Nagaraja G Devadiga
wrap your code with c:choose tag. It should do
用 c:choose 标签包装你的代码。它应该做
回答by Ashish Vaghasiya
<c:choose>
<c:when test="${not empty propertyValue}">
<option value="${fonts}" selected="selected">${fonts}</option>
</c:when>
<c:otherwise>
<option value="${fonts}">${fonts}</option>
</c:otherwise>
</c:choose>