从servlet中获取的ResultSet结果集如何传递到jsp页面并显示
servlet中连接数据库获得结果集然后遍历结果集每次遍历的结果封装到实体类user中最后把每次得到的user中放入List<User>中,然后用request.setAttribute方法进行传递,用forword方法转发
在jsp页面中用request.getAttribute方法获取
代码示例(主要代码不全):
servlet中
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/haha", "root","root");
String sql="select id,username,password from t_user ";
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
**List<User> userlist= new ArrayList<User>();
User user=null;
while(rs.next()){
user=new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
userlist.add(user);
}
request.setAttribute("userlist",userlist);**
} catch (Exception e) {
e.printStackTrace();
}finally{
if(conn !=null){
try {
conn.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if(ps !=null){
try {
ps.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if(rs !=null){
try {
rs.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
**request.getRequestDispatcher("/list.jsp").forward(request, response);**
jsp代码
<%@ page language="java" **import="java.util.*,com.bjpowernode.javaweb.entity.User"** pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'list.jsp' starting page</title>
</head>
<body>
**<%
ArrayList userlist=(ArrayList)request.getAttribute("userlist");
%>**
<h2 align="center">员工列表</h2>
<table align="center">
<tr>
<th>序号</th>
<th>姓名</th>
<th>密码</th>
<th>操作</th>
</tr>
**<%for(int i=0;i<userlist.size();i++){
User user=(User)userlist.get(i);%>
<tr><th><%=user.getId() %></th>
<th><%=user.getUsername() %></th>
<th><%=user.getPassword() %></th>
<th><a href="/prj-servlet-22/modify.jsp">修改</a><a href="/prj-servlet-22/delete.jsp">删除</a></th>
<%
} %>**
</table>
</body>
</html>