如何在jsf datatable中访问Map键

我收到错误javax.el.PropertyNotFoundException: /member/apps/cms/edit.xhtml @228,49 value="#{props.key}": Property 'key' not found on type java.util.HashMap$Values尝试显示下面的javax.el.PropertyNotFoundException: /member/apps/cms/edit.xhtml @228,49 value="#{props.key}": Property 'key' not found on type java.util.HashMap$Values时的javax.el.PropertyNotFoundException: /member/apps/cms/edit.xhtml @228,49 value="#{props.key}": Property 'key' not found on type java.util.HashMap$Values

 

这是我的contentEditorBacking的相关部分:

 @ManagedBean @ViewScoped public class ContentEditorBacking { private Map properties = new LinkedHashMap(); public Collection getProperties() throws Exception{ return properties.values(); } public static class Properties{ private String key; private String value; public Properties(String key, String value) { super(); this.key = key; this.value = value; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public String toString() { return "key=" + key + ", value=" + value + ""; } } } 

如何从我的属性映射中访问键值?

在即将推出的JSF 2.2之前, / 不支持Collection 。 它只支持List

你需要更换

 public Collection getProperties() throws Exception{ return properties.values(); } 

通过

 private List propertiesAsList; public List getProperties() throws Exception{ return propertiesAsList; } 

在地图初始化之后直接执行此操作

 propertiesAsList = new ArrayList(properties.values()); 

(注意:不要在吸气器内做!)

在JSF代码中,您尝试访问getProperties()方法返回的事物的键属性,该方法是整个集合。 你需要遍历props变量。

dataTable必须接收Collection(例如,List)。 Map不实现Collection接口。 您应该将地图转换为列表并进行修改,然后将列表转换回地图。 这是一个很好的链接,展示了如何做到这一点:

  • 在JSF页面中显示HashMap内容

当然,我不建议你在getter / setter中添加逻辑,而是使用2个不同的属性,并使getter和setter保持最干净的方式。

您的属性类需要在此处实现map接口: http : //docs.oracle.com/javase/6/docs/api/java/util/Map.html

但更好的问题是,为什么要创建自己的类? Java在SDK中提供了一个Properties类: http : //docs.oracle.com/javase/7/docs/api/java/util/Properties.html

编辑:根据OP的请求更新我的答案

更改以下行,然后修复Eclipse中的编译错误:

 public static class Properties{ 

至:

 public static class Properties implements Map { 

编辑#2:其实我的回答可能是错的。 OP没有发布他的整个xhtml文件,我做了一个不正确的假设。