对象为 中的itemValue
是否可以将对象作为itemValue标记?
例如,我有一个类Foo:
public class Foo { private int id; private String name; private Date date; }
另一个class吧
public class Bar { private Foo foos; } public class BarBean { private Set foos; }
现在在一个名为BarBean的Bean中,我需要有一个从用户那里获取当前Bar的Foo,如下所示:
—————编辑:
my converter: package ir.khorasancustoms.g2g.converters; import ir.khorasancustoms.g2g.persistance.CatalogValue; import java.util.ResourceBundle; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; @FacesConverter("ir.khorasancustoms.CatalogValueConverter") public class CatalogValueConverter implements Converter { @Override public Object getAsObject(FacesContext context, UIComponent component, String value) { SessionFactory factory = new Configuration().configure().buildSessionFactory(); Session session = factory.openSession(); try { int id = Integer.parseInt(value); CatalogValue catalogValue = (CatalogValue) session.load(CatalogValue .class, id); return catalogValue; } catch (Exception ex) { Transaction tx = session.getTransaction(); if (tx.isActive()) { tx.rollback(); } ResourceBundle rb = ResourceBundle.getBundle("application"); String message = rb.getString("databaseConnectionFailed"); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, message, message)); } finally { session.close(); } return null; } @Override public String getAsString(FacesContext context, UIComponent component, Object value) { return ((CatalogValue) value).getId() + ""; } }
和我的脸:
是的,这是可能的。
您需要编写一个将Foo转换为SelectItem
的转换器
在这里检查实施和非常好的文章
由Jigar引用的BalusC的文章提供了两个出色的解决方案。 它是通过一个转换器使用DAO或通过Strings在转发bean中来回转换。
另外一个解决方案是这两者的混合。 通过例如f:param
您可以让转换器访问EL值表达式,该表达式指向支持Bean BalusC中提到的Map。 可以参考Map来代替可能需要为每次转换访问数据库的DAO。
这允许您在
标记内使用完整的Foo对象,并在每次回发后保存对DB的可能调用。 然而,由于必须提供转换器,参数和映射,因此编码成本会增加一些额外的复杂性。
(我必须添加btw,当支持bean在视图范围或更大的范围内时,这样的Map最有效。当它在请求范围内时,它不会真正节省数据库调用)
我在Myfaces 2.0.2上,这是有效的
甚至更好
使用itemLabel默认为foo.toString() – Dunno如果重要但foos是List
而不是Set
如果使用,则不需要
@FacesConverter(forClass = Foo.class)
在FooConverter之前
- 如何通过Java中的收据打印机打印支票?
- Java:在运行时将类添加到Jar存档
- AbstractSecurityWebApplicationInitializer与AbstractAnnotationConfigDispatcherServletInitializer
- XStream的安全框架未初始化,XStream可能容易受到攻击
- 是什么让Jasper Reports抛出java.io.IOException读取字体数据?
- 如何在java中未映射的网络打印机上打印PDF?
- JTable使用TableCellRenderer更改单元格颜色
- 如何从字符串中提取数字
- 让JFace窗口在任务栏中闪烁或引起用户注意?