jsp中的嵌套问题
发布网友
发布时间:2024-10-21 18:02
我来回答
共1个回答
热心网友
时间:2024-10-21 20:25
把数据库的结果先取出来放到一个HashMap里面去,然后再迭代这个HashMap就行了。HashMap的数据结构是这样的<key,List<Task>>,这里面的key就是time值
给你写了一个例子:自己看吧:代码是基于JDK1.5(含1.5)以上版本写的
Task.java
package com.test;
public class Task {
private String taskName;
private String userName;
private String time;
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
Test.java
package com.test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Test {
public static Connection getConnection() throws Exception {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = java.sql.DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8", "dev", "dev");
conn.setAutoCommit(true);
} catch (Exception e) {
}
return conn;
}
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Map<String, List<Task>> tasks = new HashMap<String, List<Task>>();
try {
conn = getConnection();
String sqlStr = "select * from task where time order by time desc";
ps = conn.prepareStatement(sqlStr);
rs = ps.executeQuery();
while (rs.next()) {
Task task = new Task();
String time = rs.getString("time");
task.setTaskName(rs.getString("taskName"));
task.setUserName(rs.getString("userName"));
task.setTime(time);
if (tasks.containsKey(time)) {
List<Task> list = tasks.get(time);
list.add(task);
} else {
List<Task> list = new ArrayList<Task>();
list.add(task);
tasks.put(time, list);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
}
}
Set<String> it = tasks.keySet();
for (String s : it) {
System.out.println("------time-------" + s);
List<Task> ts = tasks.get(s);
for (Task t : ts) {
System.out.println("------taskName-------" + t.getTaskName() + "----userName----"+ t.getUserName());
}
}
}
}