gpt4 book ai didi

java - 在 JSF+Facelets 中迭代 HashMap.values()

转载 作者:搜寻专家 更新时间:2023-10-31 19:36:29 24 4
gpt4 key购买 nike

我正在使用 JSF/Facelets,我正在尝试迭代一些我保存在 HashMap 中的文档对象(自定义对象)。加载页面时,出现错误“在类型 java.util.HashMap$Values 上找不到属性‘名称’”。这是我的支持 bean 中的内容:

private Map<String, Document> documents = new HashMap<String, Document>();

public Collection<Document> getDocuments(){
return documents.values();
}

在我的 xhtml 页面中:

<h:dataTable id="documentTable"
value="#{DocumentManager.allDocuments}"
var="doc" rowClasses="list-row-odd, list-row-even"
headerClass="table-header" styleClass="bordered">

<h:column id="col_name">
<f:facet name="header">Name</f:facet>
${doc.name}
</h:column>
</h:dataTable>

如果我将 getDocuments 函数更改为以下内容,它会起作用(意味着表格显示无误),但我不确定为什么我需要将值放在列表中以使 JSF/Facelets 页面正确显示.

public List<Document> getDocuments(){
List<Document> rtrn = new ArrayList<Document>();
for(Document doc : documents.values())
rtrn.add(doc);
return rtrn;
}

难道我不能遍历集合吗?

最佳答案

事实证明,您不能只对 dataTable 使用任何类型的集合类型,这是有充分理由的。来自MyFaces 1.2 Spec ,值属性必须是:

An EL expression that specifies the data model that backs this table.

The value referenced by the EL expression can be of any type.

  • A value of type DataModel is used directly.
  • Array-like parameters of type Object[], java.util.List, java.sql.ResultSet or javax.servlet.jsp.jstl.sql.Result are wrapped in a corresponding DataModelthat knows how to iterate over the elements.
  • Other values are wrapped in a DataModel as a single row.

Note in particular that unordered collections, eg Set are not supported. Therefore if the value expression references such an object then the table will be considered to contain just one element - the collection itself.

从 HashSet.values() 返回的集合未排序,因此不受支持。如果是这样,您将不知道表格中的行将以何种顺序输出,并且页面刷新可能会随机重新排序。不好。

您得到的错误是,从上一段开始,它表示数据表将您的集合视为行对象,而集合没有“名称”属性。

关于java - 在 JSF+Facelets 中迭代 HashMap.values(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/310410/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com