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

29 jstl list set

我在会话中有一个Java Set,在会话中也有一个变量.我需要能够判断集合中是否存在该变量.

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

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

谢谢,亚历克斯

McD*_*ell 41

您可以使用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>
Run Code Online (Sandbox Code Playgroud)

更好的方法是使用自定义函数:

package my.package;
public class Util {

  public static boolean contains(Collection<?> coll, Object o) {
    if (coll == null) return false;
    return coll.contains(o);
  }

}
Run Code Online (Sandbox Code Playgroud)

这在TLD文件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>
Run Code Online (Sandbox Code Playgroud)

然后可以将该函数导入JSP:

<%@ 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>
Run Code Online (Sandbox Code Playgroud)

EL的下一个版本(在JEE6中到期)应该允许更直接的形式:

${numbers.contains('two')}
Run Code Online (Sandbox Code Playgroud)