如何在servlet -jsp / jsp-servlet中过滤arraylist结果?

时间:2010-11-23 06:16:40

标签: java filter arraylist

你好我的项目中的朋友我有一个arraylist在给定数据库内容的jsp页面表中显示结果,我想添加一个过滤器来显示列表中匹配的内容,

the table which is coming out is as:
student_id class_id student_name
1x0001        10         Ashish
1x2001        11         Alex
1x2002        11         Atr.
1x0001        10         Alok

.............going on...

但我希望结果只显示class_id :: 11的页面,并删除其他结果如何做到这一点?

List dataList = new ArrayList();
rs = s.getResultSet();
      while (rs.next ()){
        //Add records into data list
        dataList.add(rs.getInt("class_id"));
        dataList.add(rs.getString("name"));
        dataList.add(rs.getString("student_id"));
      }

然后通过获取arraylist在servlet中显示结果: 我想要的是将事物显示为带有arraylist而不是DB的过滤表:

the table which is coming(result???) out on servlet is as:
    student_id class_id student_name
    1x2001        11         Alex
    1x2002        11         Atr.

    .............going on...

2 个答案:

答案 0 :(得分:2)

问题出在哪里。将该条件放在SQL查询中,如where class_id = ?

答案 1 :(得分:0)

在SQL层过滤,就像Adeel说的那样。

此外, 应该使用Bean / Class / Struct来保存每条记录,而不是将所有非结构化数据方式堆积到一个ArrayList中。

尽管如此,以下代码可以满足您的要求:

public class FilterTest {
    public static int COLS_PER_RECORD = 3;

    public static void main(String[] args) {
        ArrayList dataList = populateTestData();
        printRecords(dataList);
        ArrayList filtered = filterForClassId(dataList, 2);
        printRecords(filtered);
    }

    private static ArrayList populateTestData() {
        ArrayList dataList = new ArrayList();
        ResultSet rs = s.getResultSet();
        while (rs.next()) {
            dataList.add(rs.getInt("class_id"));
            dataList.add(rs.getString("name"));
            dataList.add(rs.getString("student_id"));
        }
        return dataList;
    }

    private static ArrayList filterForClassId(ArrayList dataList,
            int classIdToFilterFor) {
        ArrayList filtered = new ArrayList();
        Integer classIdToFilterForInteger = new Integer(classIdToFilterFor);
        for (int i = 0; i < dataList.size(); i += COLS_PER_RECORD) {
            if (classIdToFilterForInteger.equals(dataList.get(i))) {
                for (int j = 0; j < COLS_PER_RECORD; j++) {
                    filtered.add(dataList.get(i + j));
                }
            }
        }
        return filtered;
    }

    private static void printRecords(ArrayList dataList) {
        System.out.println("----");
        for (int i = 0; i < dataList.size(); i += COLS_PER_RECORD) {
            System.out.println("class_id=" + dataList.get(i) + " name="
                    + dataList.get(i + 1) + " student_id="
                    + dataList.get(i + 2));
        }
        System.out.println("----");
    }
}