JSTL集和列表-检查集中是否存在项目 [英] JSTL Sets and Lists - checking if item exists in a Set

查看:71
本文介绍了JSTL集和列表-检查集中是否存在项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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用于列表和集合的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屋!

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