如果JSP中存在某些值,我需要隐藏元素
这些值存储在List中,所以我尝试了:
<c:if test="${ mylist.contains( myValue ) }">style='display:none;'</c:if>
Run Code Online (Sandbox Code Playgroud)
但是,它不起作用.
如何评估列表是否包含JSTL中的值,列表和值是字符串.
Chi*_*hii 96
没有内置功能来检查 - 你要做的是编写自己的tld函数,它接受一个列表和一个项目,并调用列表的contains()方法.例如
//in your own WEB-INF/custom-functions.tld file add this
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0"
>
<tlib-version>1.0</tlib-version>
<function>
<name>contains</name>
<function-class>com.Yourclass</function-class>
<function-signature>boolean contains(java.util.List,java.lang.Object)
</function-signature>
</function>
</taglib>
Run Code Online (Sandbox Code Playgroud)
然后创建一个名为Yourclass的类,并使用上面的签名添加一个名为contains的静态方法.我确信该方法的实现非常自我解释:
package com; // just to illustrate how to represent the package in the tld
public class Yourclass {
public static boolean contains(List list, Object o) {
return list.contains(o);
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以在你的jsp中使用它:
<%@ taglib uri="/WEB-INF/custom-functions.tld" prefix="fn" %>
<c:if test="${ fn:contains( mylist, myValue ) }">style='display:none;'</c:if>
Run Code Online (Sandbox Code Playgroud)
标记可以在站点中的任何JSP中使用.
编辑:有关tld文件的更多信息 - 这里有更多信息
Kal*_*see 64
可悲的是,我认为JSTL不支持任何东西,只是迭代所有元素来解决这个问题.过去,我在核心标记库中使用了forEach方法:
<c:set var="contains" value="false" />
<c:forEach var="item" items="${myList}">
<c:if test="${item eq myValue}">
<c:set var="contains" value="true" />
</c:if>
</c:forEach>
Run Code Online (Sandbox Code Playgroud)
运行后,如果myList包含myValue,则$ {contains}将等于"true".
tam*_*ama 26
另一种方法是使用Map (HashMap)
带有代表对象的Key,Value对.
Map<Long, Object> map = new HashMap<Long, Object>();
map.put(new Long(1), "one");
map.put(new Long(2), "two");
Run Code Online (Sandbox Code Playgroud)
在JSTL
<c:if test="${not empty map[1]}">
Run Code Online (Sandbox Code Playgroud)
如果该对存在于地图中,则应返回true
tk_*_*tk_ 12
您需要使用fn:contains()
或fn:containsIgnoreCase()
功能.
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
Run Code Online (Sandbox Code Playgroud)
...
<c:if test="${not fn:containsIgnoreCase(mylist, 'apple')}">
<p>Doesn't contain 'apple'</p>
</c:if>
Run Code Online (Sandbox Code Playgroud)
要么
<c:if test="${not fn:contains(mylist, 'Apple')}">
<p>Contains 'Apple'</p>
</c:if>
Run Code Online (Sandbox Code Playgroud)