JSTL 集合和列表 - 检查集合中是否存在项目 [英] JSTL Sets and Lists - checking if item exists in a Set
问题描述
我的会话中有一个 Java 集,会话中还有一个变量.我需要能够判断该变量是否存在于集合中.
I have a Java Set in my session and a variable also in the session. I need to be able to tell if that variable exists in the set.
我想使用 Java 为 Lists 和 Sets 提供的 contains ( Object ) 方法来测试该对象是否存在于集合中.
I want to use the contains ( Object ) method that Java has for Lists and Sets to test whether that object exists in the set.
在 JSTL 中可以做到吗?如果是这样,怎么做?:)
Is that possible to do in JSTL? If so, how? :)
谢谢,亚历克斯
推荐答案
你可以使用 JSTL 标签来做到这一点,但结果不是最优的:
You could do this using JSTL tags, but the result is not optimal:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<jsp:useBean id="numbers" class="java.util.HashSet" scope="request">
<%
numbers.add("one");
numbers.add("two");
numbers.add("three");
%>
</jsp:useBean>
<c:forEach items="${numbers}" var="value">
<c:if test="${value == 'two'}">
<c:set var="found" value="true" scope="request" />
</c:if>
</c:forEach>
${found}
</body>
</html>
<小时>
更好的方法是使用自定义函数:
A better way would be to use a custom function:
package my.package;
public class Util {
public static boolean contains(Collection<?> coll, Object o) {
if (coll == null) return false;
return coll.contains(o);
}
}
这是在 TLD 文件中定义的ROOT/WEB-INF/tag/custom.tld:
This is defined in a TLD file ROOT/WEB-INF/tag/custom.tld:
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
version="2.1">
<tlib-version>1.0</tlib-version>
<short-name>myfn</short-name>
<uri>http://samplefn</uri>
<function>
<name>contains</name>
<function-class>my.package.Util</function-class>
<function-signature>boolean contains(java.util.Collection,
java.lang.Object)</function-signature>
</function>
</taglib>
然后可以将该函数导入到您的 JSP 中:
The function can then be imported into your JSPs:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="myfn" uri="http://samplefn"%>
<html>
<body>
<jsp:useBean id="numbers" class="java.util.HashSet" scope="request">
<%
numbers.add("one");
numbers.add("two");
numbers.add("three");
%>
</jsp:useBean>
${myfn:contains(numbers, 'one')}
${myfn:contains(numbers, 'zero')}
</body>
</html>
<小时>
EL 的下一个版本(在 JEE6 中到期)应该允许更直接的形式:
The next version of EL (due in JEE6) should allow the more direct form:
${numbers.contains('two')}
这篇关于JSTL 集合和列表 - 检查集合中是否存在项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!