jsp - 使用 JSTL 检查集合大小

标签 jsp collections jstl

如何使用 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/

相关文章:

arrays - 从数据表/字典到工作表的字典

java - ASSIGNRES 类型的比较方法未定义

java - 使用 JSTL 在 JSP 中遍历 JSONArray

java - 谷歌开发人员地理图表和 DAO 对象

java - 如何在我的 JSP 页面中使用 Iterables?

java - 如何将 LinkedHashSet 集合添加到 JsonObjectBuilder 对象?

html - 在 jsp 中使用 for each loop 在 textarea 中显示数据的问题

java - 从 Spring 3.0 开始用 SpEL 替换 JSP 中的 EL

java - 更改下拉选项

java - GlassFish Http 状态 500 - 内部服务器错误