用sql语句将查询结果存入hashmap中后,怎样写一个servlet取出数据,并在jsp页面显示,最好写出代码,谢谢
这是写好的TestService.java
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import com.trms.bean.Course;
import com.trms.bean.Previous;
import com.trms.dao.DAO;
public class TestService {
public static HashMap<Integer, Previous> getPrevious(){
DAO dao = new DAO();
HashMap<Integer, Previous> map = new HashMap<Integer, Previous>();
String sql = "select * from previous";
ResultSet rs = dao.query(sql);
try {
int i = 0;
while(rs.next()){
i++;
Previous p = new Previous();
p.setcNo(rs.getInt(1));
p.setcPNo(rs.getInt(2));
p.setcName(rs.getString(3));
map.put(1, p);
}
} catch (SQLException e) {
e.printStackTrace();
}
return map;
}
public static HashMap<Integer, Course> getCourse(){
DAO dao = new DAO();
HashMap<Integer, Course> map = new HashMap<Integer, Course>();
String sql = "select * from course";
ResultSet rs = dao.query(sql);
try {
int k = 0;
while(rs.next()){
k++;
Course c = new Course();
HashMap<?, ?> map1 = getPrevious();
HashMap<Integer, Previous> map2 = new HashMap<Integer, Previous>();
int j = 0;
for(int i=0;i<map1.size();i++){
if(((Previous)map1.get(i+1)).getcPNo()==rs.getInt(1)){
j++;
map2.put(j, ((Previous)map1.get(i+1)));
}
}
c.setCNo(rs.getInt(1));
c.setCPNo(rs.getInt(2));
c.setCLen(rs.getInt(3));
c.setDescription(rs.getString(4));
c.setPrevList(map2);
map.put(k, c);
}
} catch (SQLException e) {
e.printStackTrace();
}
return map;
}
}
追问:能不能把map存进request的代码也写一下?刚接触这个,基本上一点都不懂(囧)
答案:把map存在request中,然后用EL表达式,迭代map:
<c:forEach var="item" items="${map2}">
${item.key} > ${item.value} <br>
</c:forEach>
上面的item.value应该就是Previous对象咯,你尝试一下item.value.xxx看看能不能正常取值?
上一个:怎么样使用jsp代码实现交互式网页制作, 不希望得到从别人那里复制过来的回答
下一个:请帮我看看以下的两个jsp代码。怎么回事,我看着没有什么问题啊,就是编译不出来,请大家帮我看看,在此重