How to filter arraylist results in servlet-jsp/jsp-servlet?
hello friends in my project i have an arraylist showing results in a jsp page table of given contents of database, i want to add a filter to it to show only the matched contents from list,
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...
but i want the result to display page only for class_id::11 and remove other results how to do that?
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"));
}
and then showing result in servlet by getting arraylist: what i want is to display the matter as a filtered table with arraylist not DB as:
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...
Where is the problem. Put that condition in the SQL query like this, where class_id = ?
.
You should filter at the SQL layer, like Adeel said.
Also, you should use a Bean / Class / Struct to hold each record, rather than piling all data unstructured way into a single ArrayList.
Nevertheless, the following code does what you ask:
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("----");
}
}
精彩评论