我有一个Map
键/值,我在 @PostConstruct
中初始化如下:
Map<String, String> myMap;
@PostConstruct
public void init() {
myMap=new LinkedHashMap<String, String>();
myMap.put("myKey","myValue");
}
public Map<String, String> getMyMap() {
return myMap;
}
public void setMyMap(Map<String, String> myMap) {
this.myMap = myMap;
}
当我尝试使用 <ui:repeat>
迭代此 map 时如下所示,我在 Map 的 getter 上设置了一个断点,我注意到它没有被调用,因此没有打印任何内容:
<ice:panelGroup>
<ui:repeat items="#{myBean.myMap}" var="entry" varStatus="loop">
<input type="checkbox" name="myCheckBoxes" value="#{entry.value}" />
<span class="#{fn:contains(entry.value,'g') ? 'bold-style' : ''}">#{entry.key}</span>
</ui:repeat>
</ice:panelGroup>
但是当用 <c:foreach>
替换上面的代码时,一切正常,并且列表按预期打印,您知道为什么我会出现这种行为吗?
最佳答案
更新: JSF 2.3(自 2017 年起)支持此 out of the box .
遗憾的是,UIData
和 UIRepeat
不支持在 JSF 中迭代 map 。
如果这让您感到困扰(我想确实如此),请对以下问题进行投票,并在可能的情况下发表评论来解释您对此的感受:
http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-479
同时,您可以使用一些小帮助程序代码迭代 Map:
/**
* Converts a Map to a List filled with its entries. This is needed since
* very few if any JSF iteration components are able to iterate over a map.
*/
public static <T, S> List<Map.Entry<T, S>> mapToList(Map<T, S> map) {
if (map == null) {
return null;
}
List<Map.Entry<T, S>> list = new ArrayList<Map.Entry<T, S>>();
list.addAll(map.entrySet());
return list;
}
然后在 *-taglib.xml
文件中定义一个 EL 函数,如下所示:
<namespace>http://example.com/util</namespace>
<function>
<function-name>mapToList</function-name>
<function-class>com.example.SomeClass</function-class>
<function-signature>java.util.List mapToList(java.util.Map)</function-signature>
</function>
最后在 Facelet 上使用它,如下所示:
<html xmlns:util="http://example.com/util">
<ui:repeat value="#{util:mapToList(someDate)}" var="entry" >
Key = #{entry.key} Value = #{entry.value} <br/>
</ui:repeat>
关于jsf - 用户界面 :repeat doesn't work with Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8552804/