【发布时间】:2015-11-13 05:33:13
【问题描述】:
我正在尝试从selectOneMenu 获取一个具有名字、姓氏等字段的对象。这是我的表格:
<h:form>
<p:outputLabel value="Persons: " />
<p:selectOneMenu value="#{personBean.person}">
<f:selectItem itemLabel="Select Person" itemValue="" noSelectionOption="true"/>
<f:selectItems itemLabel="#{person.firstName}" itemValue="#{person}" var="person" value="#{personBean.persons}" />
</p:selectOneMenu>
<br /><br />
<p:commandButton value="Submit"
action="#{personBean.showSomething()}" icon="ui-icon-check" />
我不明白..我哪里出错了?我怎样才能得到那个对象?
我已经尝试了几天,但我还没有设法解决这个问题......
我尝试使用Converter,但我不断收到 NPE。
编辑
这是我的转换器:(我试图在我的 DAO 的帮助下从我的 postgres 数据库中获取对象)
@Named
@FacesConverter(forClass=Person.class)
public class PersonConverter implements Converter {
@Inject
private PersonDao personDao;
@Override
public Object getAsObject(FacesContext arg0, UIComponent component, String submittedValue) {
if (submittedValue == null || submittedValue.isEmpty()) {
return null;
}
try {
Person p = personDao.findById(Long.valueOf(submittedValue));
return p;
} catch (NumberFormatException e) {
throw new ConverterException(new FacesMessage(submittedValue + " is not a valid Person ID"), e);
}
}
@Override
public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
if (arg2 == null) {
return "";
}
if (arg2 instanceof Person) {
return String.valueOf(((Person) arg2).getId());
} else {
throw new ConverterException(new FacesMessage(arg2 + " is not a valid Person"));
}
}
}
这是我得到 NPE Person p = personDao.findById(Long.valueOf(submittedValue));
find() 方法适用于其他任何地方......
当我使用调试器时,我注意到 personDao 为空。我该如何解决这个问题?
【问题讨论】:
-
仅当我使用转换器时。如果没有,
personBean.showInfo()甚至没有被调用,所以它没有返回任何东西。 -
请添加更多信息。就像您获得 NPE 的堆栈跟踪一样。另外,itemValue 不应该是#{person} 吗?而不是 #{person.firstName}?
-
感谢您指出这一点!