Reputation: 222
Hi friends i am trying iterate through a list that contains list of objects I am trying to iterate through that list . each element of the list is a 'object'. I accessing the variables of that 'object' with the help of c:forEach . I am getting the values. but the same again and again . I dont know if i am doing any mistake while adding objects to list in the servlet or in the jsp while iterating through them.
Here is my servlet code
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);
Here is my 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 -->
Please help . Sorry for any confusion.
Upvotes: 0
Views: 1837
Reputation: 6608
The problem with your code is you're always updating a single instance of FileInfo through fileInfo
variable, so in each iteration you're just overwriting a single object's state.
FileInfo fileInfo = new FileInfo();
--------
while(rs.next()) {
// updating fileInfo from result set
}
Move that FileInfo
into the while loop like below
while(rs.next()) {
FileInfo fileInfo = new FileInfo();
// update new fileInfo from result set and add to fileInfoList
}
Upvotes: 1
Reputation: 21961
You are adding same object again and again. You need to initiate FileInfo
inside while loop
while(rs.next()) {
FileInfo fileInfo= new FileInfo();
.....
fileInfoList.add(fileInfo)
}
Upvotes: 1
Reputation: 52185
Move this line: FileInfo fileInfo = new FileInfo();
within the while
loop:
while(rs.next()) {
FileInfo fileInfo = new FileInfo();
....
As is, you are creating only one instance and keep updating the same. Most likely you keep on seeing the last element you are pulling from the database multiple times.
Upvotes: 1