如何使用 JSTL 检查集合的大小?
类似于:
<c:if test="${companies.size() > 0}">
</c:if>
最佳答案
<c:if test="${companies.size() > 0}">
</c:if>
此语法仅适用于 EL 2.2 或更高版本(Servlet 3.0/JSP 2.2 或更高版本)。如果您因为使用 JSPX 或 Facelets 而不是 JSP 而遇到 XML 解析错误,请使用 gt
而不是 >
。
<c:if test="${companies.size() gt 0}">
</c:if>
如果您确实遇到 EL 解析错误,那么您可能使用的是太旧的 EL 版本。那么您将需要 JSTL fn:length()
函数。来自 the documentation :
length( java.lang.Object) - Returns the number of items in a collection, or the number of characters in a string.
将其放在 JSP 页面的顶部以允许 fn
命名空间:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
或者,如果您使用 JSPX 或 Facelets:
<... xmlns:fn="http://java.sun.com/jsp/jstl/functions">
并在您的页面中像这样使用:
<p>The length of the companies collection is: ${fn:length(companies)}</p>
因此要测试集合的长度:
<c:if test="${fn:length(companies) gt 0}">
</c:if>
或者,对于这种特定情况,您也可以简单地使用 EL empty
运算符:
<c:if test="${not empty companies}">
</c:if>
关于jsp - 使用 JSTL 检查集合大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60773517/