我试图从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 db中获得对象)
@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是空的。我怎样才能解决这个问题?
-
在页面中:
<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}" /> <f:converter binding="#{personConverter}" /> <f:attribute name="attrpersons" value="#{personBean.persons}" /> </p:selectOneMenu>
-
在Person bean中:
你必须实现toString和equals方法
-
最后你必须添加转换器类:
@Named public class PersonConverter implements Converter{ public PersonConverter(){} @Override public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) { List<Person> persons = (List<Person>)component.getAttributes().get("attrpersons"); if (submittedValue.trim().equals("")) { return null; } else { Iterator<Person> it = persons.iterator(); while(it.hasNext()){ Person p = it.next(); if(p.toString().equals(submittedValue)) return p; } } return null; } @Override public String getAsString(FacesContext facesContext, UIComponent component, Object value) { if (value == null) { return ""; } else { return value.toString(); } } }