如何遍历jsp中的对象列表

时间:2015-03-17 16:26:13

标签: java jsp servlets

朋友们,我正在尝试遍历包含对象列表的列表 我试图遍历该列表。列表中的每个元素都是一个'对象'。 我访问了该对象的变量'在c:forEach的帮助下。我正在获得价值观。但一次又一次。 我不知道在将对象添加到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 -->

请帮忙。抱歉有任何困惑。

3 个答案:

答案 0 :(得分:1)

FileInfo fileInfo = new FileInfo();循环中移动此行:while

while(rs.next()) {
FileInfo fileInfo = new FileInfo();
....

按原样,您只创建一个实例并继续更新。很可能你会多次看到你从数据库中提取的最后一个元素。

答案 1 :(得分:1)

您正在反复添加相同的对象。你需要在while循环中启动FileInfo

  while(rs.next()) {
     FileInfo fileInfo= new FileInfo();
          .....
     fileInfoList.add(fileInfo)
  }

答案 2 :(得分:1)

您的代码的问题是您始终通过fileInfo变量更新FileInfo的单个实例,因此在每次迭代中您只是覆盖单个对象的状态。

   FileInfo fileInfo = new FileInfo();
   --------
    while(rs.next()) {
      // updating fileInfo from result set
   }

FileInfo移动到while循环中,如下所示

   while(rs.next()) {
      FileInfo fileInfo = new FileInfo();
      // update new fileInfo from result set and add to fileInfoList
   }
相关问题