You can do this with 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>
It is best 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 the 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>
Then the function can be imported into your 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>
The next version of EL (due to JEE6) should allow a more direct form:
${numbers.contains('two')}
McDowell Jul 05 '09 at 14:22 2009-07-05 14:22
source share