我再次遇到麻煩。我的觀點是: 在我的項目中,我需要一個轉換器(顯然)將SelectOneMenu組件中的項目轉換爲相應bean中的列表屬性。在我的JSF頁面我有:SelectOneMenu中的JSF轉換器問題
<p:selectOneMenu id="ddlPublicType" value="#{publicBean.selectedPublicType}" effect="fade" converter="#{publicBean.conversor}" >
<f:selectItems value="#{publicoBean.lstPublicTypes}" var="pt" itemLabel="#{pt.label}" itemValue="#{pt.value}"></f:selectItems>
</p:selectOneMenu>
我的bean是:
@ManagedBean(name = "publicBean")
@RequestScoped
public class PublicBean {
// Campos
private String name; // Nome do evento
private TdPublicType selectedPublicType = null;
private List<SelectItem> lstPublicTypes = null;
private static PublicTypeDAO publicTypeDao; // DAO
static {
publicTypeDao = new PublicTypeDAO();
}
// Construtor
public PublicoBean() {
lstPublicTypes = new ArrayList<SelectItem>();
List<TdPublicType> lst = publicTypeDao.consultarTodos();
ListIterator<TdPublicType> i = lst.listIterator();
lst.add(new SelectItem("-1","Select..."));
while (i.hasNext()) {
TdPublicType actual = (TdPublicType) i.next();
lstPublicTypes.add(new SelectItem(actual.getIdPublicType(), actual.getNamePublicType()));
}
}
// Getters e Setters
...
public Converter getConversor() {
return new Converter() {
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
// This value parameter seems to be the value i had passed into SelectItem constructor
TdPublicType publicType = null; // Retrieving the PublicType from Database based on ID in value parameter
try {
if (value.compareTo("-1") == 0 || value == null) {
return null;
}
publicType = publicTypeDao.findById(Integer.parseInt(value));
} catch (Exception e) {
FacesMessage msg = new FacesMessage("Error in data conversion.");
msg.setSeverity(FacesMessage.SEVERITY_ERROR);
FacesContext.getCurrentInstance().addMessage("info", msg);
}
return publicType;
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
return value.toString(); // The value parameter is a TdPublicType object ?
}
};
}
...
}
在的getAsObject()方法,數值參數似乎我已經傳遞到了SelectItem構造函數的值。但在getAsString()方法中,該值也似乎是一個Id的字符串表示形式。此參數不應該是TdPublicType類型?我的代碼有什麼問題嗎?
我是否需要重載**的toString()** TdPublicType的?在** getAsString()**方法內部生成一個異常,說不可能從String轉換爲TdPublicType。 –
然後模型值顯然不是'TdPublicType'類型。事實上,您使用'itemValue =「#{pt.value}」'而不是'itemValue =「#{pt}」'。相應地修復它。 – BalusC
他仍然返回一個Integer作爲組件的支持模型,但我已經將itemValue屬性更改爲#{pt}。 –