我尝试以MVC模式创建Web应用程序以显示来自DB的数据
JSP:
<c:forEach var="pro" items="${list}">
<tr>
<td><c:out value="${pro.reqno}"></c:out></td>
<td><c:out value="${pro.leave_Type}"></c:out></td>
<td><c:out value="${pro.no_of_days}"></c:out></td>
<td><c:out value="${pro.status}"></c:out></td>
<td><c:out value="${pro.balanceUnits}"></c:out></td>
<td><c:out value="${pro.totalUnits}"></c:out></td>
</tr>
</c:forEach>
Servlet的:
ArrayList temp = summary.getSummary(objUsr);
request.setAttribute("list", temp);
RequestDispatcher rd = request.getRequestDispatcher("JSP/login-success.jsp");
DAO类:
public ArrayList<LeaveSummary> getSummary(LeaveSummary objUsr) throws SQLException {
PreparedStatement stmt = null;
ArrayList<LeaveSummary> rowArray = new ArrayList<LeaveSummary>();
ResultSet rs = null;
try {
LeaveSummary getValuesFromDb = new LeaveSummary();
Connection con = ConnectionProvider.getCon();
stmt = con.prepareStatement("SELECT * FROM create_request where username=?");
stmt.setString(1, objUsr.getUser_name());
rs = stmt.executeQuery();
while (rs.next()) {
getValuesFromDb.setReqno(rs.getInt(1));
getValuesFromDb.setUser_name(rs.getString(2));
getValuesFromDb.setNo_of_days(rs.getInt(4));
getValuesFromDb.setLeave_Type(rs.getString(3));
getValuesFromDb.setStatus(rs.getString(6));
getValuesFromDb.setTotalUnits(rs.getInt(7));
getValuesFromDb.setBalanceUnits(rs.getInt(8));
rowArray.add(getValuesFromDb);
}
}
catch(Exception e)
{
e.printStackTrace();
}
数据库表:
1 san Casual 1 sicks pending 10 9
2 san Others 2 Functional pending 10 8
但是它仅打印第二行(即最近添加的行),我该如何打印表中的两行
解决方法:
创建一个新实例
LeaveSummary getValuesFromDb = new LeaveSummary();
在您的while循环中.您没有为数据库中的每条记录创建一个LeaveSummary的新实例.因此,每次循环结果集时都会重写同一对象.这就是为什么最后一个记录仅存在于列表中的原因.