List JSTL集合和列表-检查集合中是否存在项

List JSTL集合和列表-检查集合中是否存在项,list,jstl,set,List,Jstl,Set,我的会话中有一个Java集,会话中也有一个变量。我需要知道这个变量是否存在于集合中 我想使用Java用于列表和集合的contains(Object)方法来测试集合中是否存在该对象 在JSTL中可以这样做吗?如果是,怎么做?:) 谢谢, Alex您可以使用JSTL标记来实现这一点,但结果不是最佳的: <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <body> <

我的会话中有一个Java集,会话中也有一个变量。我需要知道这个变量是否存在于集合中

我想使用Java用于列表和集合的contains(Object)方法来测试集合中是否存在该对象

在JSTL中可以这样做吗?如果是,怎么做?:)

谢谢,
Alex

您可以使用JSTL标记来实现这一点,但结果不是最佳的:

<%@ 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>

如果您使用的是Spring Framework,则可以使用Spring标记库和SpEL:

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
---
<spring:eval var="containsValue" expression="yourList.contains(yourValue)" />

Contains (true or false): ${containsValue}

---
包含(true或false):${containsValue}

+1用于使用自定义功能。这是正确的方法,可以重复使用:)
<?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>
<%@ 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>
${numbers.contains('two')}
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
---
<spring:eval var="containsValue" expression="yourList.contains(yourValue)" />

Contains (true or false): ${containsValue}