JSTL Sets and Lists - checking if item exists in a Set

前端 未结 2 972
暗喜
暗喜 2020-12-23 11:49

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.

I want to use the contains ( Obj

相关标签:
2条回答
  • 2020-12-23 12:28

    If you are using Spring Framework, you can use Spring TagLib and SpEL:

    <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
    ---
    <spring:eval var="containsValue" expression="yourList.contains(yourValue)" />
    
    Contains (true or false): ${containsValue}
    
    0 讨论(0)
  • 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);
      }
    
    }
    

    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>
    

    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>
    

    The next version of EL (due in JEE6) should allow the more direct form:

    ${numbers.contains('two')}
    
    0 讨论(0)
提交回复
热议问题