2015-07-10 66 views
0

我有一個jsf 2選擇輸入與轉換器連接到selectentries。我的對象有一個很長的id域,它應該是值。當我的轉換器被調用時,它將被調用整個選擇項目列表(List<SimpleEntityGroup>)而不是SimpleEntityGroup,因此我只能返回組的.getId()jsf selectOneMenu轉換器獲取項目列表作爲值

調試輸出是:

轉換爲字符串

[SimpleEntityGroup [ID = 1,名稱= 1組],SimpleEntityGroup [ID = 2,名稱=第2組],SimpleEntityGroup [ID = 3,name = Group 3]]

我期待的方法被調用3次,每次只有一個SimpleEntityGroup,並不是所有的3次都是一次列表。該方法應該返回一個字符串,如果我返回「1」,那麼我選擇的所有值都是1,所以我知道它是在正確的位置使用轉換器。爲什麼這樣稱呼它?

<h:selectOneMenu value="#{simpleEntityBacking.simpleEntity.group}" converter="SimpleEntityGroupConverter"> 
    <f:selectItems value="#{simpleEntityBacking.groups}" var="c" 
     itemLabel="#{c.name}" itemValue="#{c.id}" /> 
</h:selectOneMenu> 

這是我支持bean - getter和setter和所有省略:

public class SimpleEntityBacking { 
    private static final Logger L = Logger.getLogger(SimpleEntityBacking.class); 

    @ManagedProperty(value="#{simpleEntity}") 
    private SimpleEntity simpleEntity; 

    @ManagedProperty(value="#{groups}") 
    private List<SimpleEntityGroup> groups; 

    @EJB 
    private SimpleEntityDao ed; 

    /** 
    * 
    */ 
    public SimpleEntityBacking() { 

    } 

這裏是我的轉換器:

/* (non-Javadoc) 
    * @see javax.faces.convert.Converter#getAsObject(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.String) 
    */ 
    @Override 
    public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) { 
     return ed.getGroupById(new Long(arg2)); 
    } 

    /* (non-Javadoc) 
    * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object) 
    */ 
    @Override 
    public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) { 
     L.debug("Converting to String"); 
     L.debug(arg2); 
     SimpleEntityGroup g = (SimpleEntityGroup) arg2; 
     return g.getId().toString(); 
    } 

回答

0

找到了答案,選擇需要看起來像這樣:

   <h:selectOneMenu value="#{simpleEntityBacking.simpleEntity.group}" converter="#{simpleEntityGroupConverter}"> 
        <f:selectItems value="#{simpleEntityBacking.groups}" var="c" 
         itemLabel="#{c.name}" /> 
       </h:selectOneMenu> 

請注意轉換器周圍有一個#{},並且itemValue未指定。現在

,該轉換器看起來像這樣:

@ManagedBean 
@ApplicationScoped 
public class SimpleEntityGroupConverter implements Converter { 
    private static final Logger L = Logger.getLogger(SimpleEntityGroupConverter.class); 

    @EJB 
    private SimpleEntityDao ed; 

的JSF轉換註釋的類不允許EJB注入,所以你必須標註爲管理bean,做價值=#{ }中選擇。