2017-01-23 153 views
0

我在我的應用程序中使用PrimeFaces 5.1我使用高級下拉菜單來顯示學生名稱。我的問題是如果同一高級下拉選項用於教授,職員和部門詳細信息。現在我對每個轉換器使用單獨的類,只需修改轉換器動態更改類名稱

**Object value1 =resolver.getValue(facesContext.getELContext(), null, "Student"); 
Student service = (Student) value1;** 

line。 我的疑問是如何替換類名以便爲所有轉換器動態使用它?

XHTML

<p:selectOneMenu value="#{Student.studentName}" var="bean" 
    converter="StudentConvertor" > 
<f:selectItems value="#{Student.studentNameList}" var="stuVar"  
    itemLabel="#{stuVar.studName}" itemValue="#{stuVar}"/> 
<p:column> 
<h:outputText value="#{bean.studName}"/> 
</p:column> 
<p:ajax event="change" update="studentPanel" 
    listener="#{Student.studentChangeAction}"/> 
</p:selectOneMenu> 

的Java

public class StudentConvertor implements Converter 
{ 

    @Override 
    public Object getAsObject(FacesContext context, UIComponent component, String value) 
    { 
     if ((value != null) && (value.trim().length() > 0)) 
     { 
      try 
      { 
       FacesContext facesContext = FacesContext.getCurrentInstance(); 
       ELResolver resolver = facesContext.getApplication().getELResolver(); 
       Object value1 = resolver.getValue(facesContext.getELContext(), null, "Student"); 
       Student service = (Student) value1; 

       if (service != null) 
       { 
        for (Integer studentId : service.getStudentNameList()) 
        { 
         if (Integer.parseInt(value) == studentId) 
         { 
          return studentId; 
       } 
        } 
       } 
       return null; 
      } 
      catch (NumberFormatException e) 
      { 
       throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid value.")); 
      } 
     } 



     return null; 
    } 

    @Override 
    public String getAsString(FacesContext context, UIComponent component, Object value) 
    { 
     if (value != null) 
     { 
      return String.valueOf(((String) value).getStudentId()); 
     } 


     return null; 
    } 
} 

回答

0

如果要顯示所有三個類別相同的信息,比方說編號和名稱,你可以嘗試使用繼承:

public class Item{ 
    private Integer Id; 
    private String name; 
    //get + set for both 
} 
public class Student extends Item{} 
public class Staff Item{} 
public class Department extends Item{} 

然後改變你的服務的方法:

public List<Item> getStudentList(); 
public List<Item> getStaffList(); 
public List<Item> getDepartmentList(); 

最後,在你的XHTML:

<f:selectItems value="#{Student.studentNameList}" var="item"  
    itemLabel="#{item.name}" itemValue="#{item.id}"/> 
<f:selectItems value="#{Staff.staffNameList}" var="item"  
    itemLabel="#{item.name}" itemValue="#{item.id}"/> 
<f:selectItems value="#{Department.departmentNameList}" var="item"  
    itemLabel="#{item.name}" itemValue="#{item.id}"/>