使用 JSTL 检查集合大小 [英] Check a collection size with JSTL

查看:18
本文介绍了使用 JSTL 检查集合大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 JSTL 检查集合的大小?

How can I check the size of a collection with 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 而不是 >.

This syntax works only in EL 2.2 or newer (Servlet 3.0 / JSP 2.2 or newer). If you're facing a XML parsing error because you're using JSPX or Facelets instead of JSP, then use gt instead of >.

<c:if test="${companies.size() gt 0}">

</c:if>

如果您确实遇到了 EL 解析错误,那么您可能使用的是太旧的 EL 版本.那么您将需要 JSTL fn:length() 函数.来自文档:

If you're actually facing an EL parsing error, then you're probably using a too old EL version. You'll need JSTL fn:length() function then. From the documentation:

length( java.lang.Object) - 返回集合中的项目数,或字符串中的字符数.

length( java.lang.Object) - Returns the number of items in a collection, or the number of characters in a string.

把这个放在JSP页面的顶部以允许fn命名空间:

Put this at the top of JSP page to allow the fn namespace:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

或者,如果您使用的是 JSPX 或 Facelets:

Or if you're using JSPX or Facelets:

<... xmlns:fn="http://java.sun.com/jsp/jstl/functions">

并在您的页面中像这样使用:

And use like this in your page:

<p>The length of the companies collection is: ${fn:length(companies)}</p>

所以要测试集合的长度:

So to test with length of a collection:

<c:if test="${fn:length(companies) gt 0}">

</c:if>

或者,对于这种特定情况,您也可以简单地使用 EL empty 运算符:

Alternatively, for this specific case you can also simply use the EL empty operator:

<c:if test="${not empty companies}">

</c:if>

这篇关于使用 JSTL 检查集合大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆