2012-06-17 37 views
1

我已Collection<Edition> selectedEditions;。當我重複這樣的:如何將Collection轉換爲jsf中的實體對象?

Collection<Edition> edlist=(java.util.Collection)selectedEditions;   
for(Edition ed:edlist){ // error at this line 
      EditionID=ed.getEditionID(); 
      NewspaperID=ed.getNewspaper().getNewspaperID(); 
      StateID=ed.getCity().getState().getStateID(); 
      System.out.print("nid..........."+NewspaperID); 
      System.out.print("sid..........."+StateID); 
     } 

然後提示錯誤,如:java.lang.ClassCastException:java.lang.String中不能轉換到entity.Edition
我消氣二傳:

public Collection<Edition> getSelectedEditions() { 
       return selectedEditions; 
} 
public void setSelectedEditions(Collection<Edition> selectedEditions) { 
     this.selectedEditions = selectedEditions; 
    } 

       </h:selectManyCheckbox> 
          <h:dataTable id="dt1" value="#{adcreateBean.selectedEditions}" var="it" styleClass="nostyle" width="100%"> 
             <f:facet name="header"> 
              <h:outputText value="You have selected :" /> 
             </f:facet> 
             <h:column> 
              <h:outputText value="#{it}" /> 
            </h:column> 
            </h:dataTable> 

那麼,我該如何投向entity.Edition? 正如在回答這個問題([How can I get multiselected checkbox value in jsf?))中所說的,我該如何轉換?

How can I get multiselected checkbox value in jsf?

回答

2

正如評論/在your previous question回答,您只需要創建一個自定義Converter其中StringEdition之間轉換。您只需創建一個實現javax.faces.convert.Converter的類,然後相應地實現這些方法。

@FacesConverter("editionConverter") 
public class EditionConverter implements Converter { 

    @Override 
    public Object getAsString(FacesContext context, UIComponent component, Object object) { 
     // Write code yourself which converts from Edition object to its unique 
     // String representation. This string will then be used in HTML and HTTP. 
    } 

    @Override 
    public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) { 
     // Write code yourself which converts from unique String representation 
     // back to Edition object. This object will then be used in JSF model. 
    } 

} 

通常,技術ID被用作唯一的String表示法。這是一個基本開球例如:

@FacesConverter("editionConverter") 
public class EditionConverter implements Converter { 

    @Override 
    public Object getAsString(FacesContext context, UIComponent component, Object object) { 
     Long id = (object instanceof Edition) ? ((Edition) object).getId() : null; 
     return (id != null) ? String.valueOf(id) : null; 
    } 

    @Override 
    public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) { 
     Long id = (submittedValue != null) ? Long.valueOf(submittedValue) : null; 
     return (id != null) ? someEditionService.find(id) : null; 
    } 

} 

最後使用它的<h:selectManyCheckbox>

<h:selectManyCheckbox ... converter="editionConverter"> 

請注意,這是絕對不一樣的鑄件。 Edition根本不是超類或String的子類。要了解究竟是什麼鑄件,請閱讀Oracle's own basic Java tutorial on the subject

相關問題