嗨 friend 们,我正在尝试迭代包含对象列表的列表 我正在尝试遍历该列表。列表中的每个元素都是一个“对象”。 我在 c:forEach 的帮助下访问该“对象”的变量。我正在获取值(value)观。但还是一样一次又一次。 我不知道在迭代对象时将对象添加到 servlet 或 jsp 中的列表中是否犯了任何错误。
这是我的 servlet 代码
FileInfo fileInfo = new FileInfo();
List<FileInfo> fileInfoList = new ArrayList<FileInfo>();
HashMap<String, String> uploadHistory = new HashMap<String, String>();
while(rs.next()) {
fileInfo.setFile_id(rs.getString("file_id"));
fileInfo.setFile_name(rs.getString("file_name"));
fileInfo.setUpload_time(rs.getString("upload_time"));
fileInfo.setUsername(rs.getString("username"));
fileInfoList.add(fileInfo);
uploadHistory.put(rs.getString("file_name"),rs.getString("upload_time"));
}
request.setAttribute("uploadHistory",uploadHistory);
request.setAttribute("fileInfo",fileInfo);
request.setAttribute("fileInfoList", fileInfoList);
RequestDispatcher rd = request.getRequestDispatcher("/UploadHistoryJsp");
rd.forward(request, response);
这是我的jsp
<div class="panel-body">
<table id="uploadHistoryTable" class="table">
<thead>
<tr>
<th><strong>File Name</strong></th>
<th><strong>Date & Time</strong></th>
</tr>
</thead>
<tbody>
<c:forEach var="uploaded" items="${fileInfoList}">
<tr>
<td><a href="${pageContext.request.contextPath}/DownloadServlet?f=${uploaded.file_name}&p=${uploaded.username}">${uploaded.file_name}</a></td>
<td>${uploaded.upload_time}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div><!-- panel-body -->
请帮忙。抱歉造成任何困惑。
最佳答案
在 while
循环中移动此行:FileInfo fileInfo = new FileInfo();
:
while(rs.next()) {
FileInfo fileInfo = new FileInfo();
....
现在,您只创建一个实例并不断更新相同的实例。您很可能会多次看到从数据库中提取的最后一个元素。
关于java - jsp中如何遍历对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29104493/