使用picklist生成ArrayList并在数据库中查找匹配值

时间:2012-03-22 01:32:34

标签: jsf

我有一个名为“newSymptomList”的数组列表,其中包含由选择列表目标生成的症状ID列表(例如[1,3,4])。我想通过每个症状并从数据库中获取相关的症状名称,尽管我被困在while循环中。

选取列表:

<rich:pickList id="plID" listWidth="10em" 
                        value="#{sym.newSymptomList}" 
                        sourceCaption="Symptoms" 
                        targetCaption="Selected Symptoms">
                    <!--List of all Symptoms-->
                    <f:selectItems value="#{sym.allSym}" var="c"
                                   itemLabel="#{c.symptomName}" itemValue="#{c.symptomId}"/>
</rich:pickList>

SymptomBean中的相关代码:

private List<Symptom> newSymptomList = new ArrayList<Symptom>();

public List getNewSymptomList()
{
  return newSymptomList;
}

public void setNewSymptomList(List<Symptom> newSymptomList )
{
  this.newSymptomList = newSymptomList; 
}

//Here is the code which returns a list of matching symptom names:

public List getSymNames() {
    List selectedSymptoms= new ArrayList(); 
    int i = 0;
    try
    {
        Class.forName("com.mysql.jdbc.Driver");
        con = ...
        ps = con.createStatement();
        rs = ps.executeQuery("select * from symptoms");
        while (rs.getString(1)== newSymptomList) {
            //getString(1) is symptomID and getString(2) is symptomName
            selectedSymptoms.add(i,new Symptom(rs.getString(1), rs.getString(2)));
            i++;
        }
    }//end of try

    catch (Exception e)
    {
        System.out.println("Error Data : " + e.getMessage());
    }

    return selectedSymptoms;
}

1 个答案:

答案 0 :(得分:1)

你正朝着达到要求的方向走错路。您allSym列表中的<f:selectItems>列表中的症状名称已经List<Symptom>。您的错误是您将所选症状设置为List<String>,而实际上它应该是#{c.symptomId}String实际上是什么类型(似乎ResultSet#getString()为你试图通过ClassCastException得到它,这不是一个理智的类型,但除此之外),否则你会在迭代它时获得private List<String> newSymptomList; // +getter+setter.

相应修复:

allSym

最后,你可以通过同一个bean中已有的Symptom列表来获取List<Symptom> selectedSymptoms = new ArrayList<Symptom>(); for (Symptom symptom : allSym) { if (newSymptomList.contains(symptom.getSymptomId())) { selectedSymptoms.add(symptom); } } // ... 个对象。

newSymptomList

另一种方法是让List<Symptom>保持真实itemValue并将<f:selectItems>的{​​{1}}修改为#{c}而不是#{c.symptomId} 。您只需要实现javax.faces.converter.Converter,以便JSF能够在Symptom及其唯一String表示之间自动转换。有关示例,另请参阅our <h:selectOneMenu> tag wiki page