我有一个豆子:
public ProjectServiceImpl {
public List<Project> getAllProjects () { ... }
}
我想将所有这些项目列为<h:selectManyListbox>
. 当用户选择一个或多个项目并按下提交按钮时,所选项目应转换为项目。
我对如何列出项目以及对应的转换器应该是什么样子感到有些困惑?
您需要实现Converter#getAsString()
所需的 Java 对象以唯一的字符串表示形式表示,该字符串表示形式可用作 HTTP 请求参数。在这里使用数据库技术 ID(主键)非常有用。
public String getAsString(FacesContext context, UIComponent component, Object value) {
// Convert the Project object to its unique String representation.
return String.valueOf(((Project) value).getId());
}
然后您需要实现Converter#getAsObject()
,以便可以将 HTTP 请求参数(根据定义String
)转换回所需的 Java 对象(Project
在您的情况下)`。
public Object getAsObject(FacesContext context, UIComponent component, String value) {
// Convert the unique String representation of Project to the actual Project object.
return projectDAO.find(Long.valueOf(value));
}
最后只需将此转换器与所讨论的对象类型相关联,JSF 将在Project
进入图片时处理转换,无需指定 aconverterId
或 a f:converter
:
<converter>
<converter-for-class>com.example.Project</converter-for-class>
<converter-class>com.example.ProjectConverter</converter-class>
</converter>
这样你就可以创造SelectItem
价值Project
。
您可以从这篇博客文章中获得一些背景信息和更多想法:http: //balusc.blogspot.com/2007/09/objects-in-hselectonemenu.html
要列出 a 中的项目,<h:selectManyListbox>
您需要使用<f:selectItems>
并将值指向SelectItem
对象列表。
我通常处理此问题的方法是遍历项目并将每个项目转换为SelectItem
. 同时,我也将项目存储在 aHashMap
中,使用SelectItem
value 作为 key。然后当您需要获取项目对象列表时,您可以循环选择值并从地图中抓取对象。
如果您不想创建HashMap
,您可以使用Project
List 在列表中的位置作为SelectItem
值并以这种方式查找项目。