2011-06-23 22 views
0

在我的第一个servlet的地方我产生名单如下如何访问列表<>使用C:的forEach?

List<Image> imageId = imageDAO.listNames(image); 

request.setAttribute("imageId", imageId); 

//Redirect it to home page 
request.getRequestDispatcher("/webplugin/jsp/profile/photos.jsp").forward(request, response); 

它获取的imageId名单与c:forEach

<c:forEach items="${imageId}" var="image"> 
    <img src="Photos/${image.photoid}"> 
</c:forEach> 

帮助显示在JSP我有具有PHOTOID一个图像bean类作为其属性

在第二个servlet被映射到Photos URL模式我带来每张照片。

问题:

  1. 我得到遍历没有时间相同的图像,等于在imageId列表中的项目数量。假设imageId在它的List中有五个imageid,那么同样的图像会在我的JSP中显示五次。如何从中检索每个id

编辑:这是我的imageDAO.listNames()方法来获得PHOTOID是有问题的,而retreiving图像,并把它在List<Image>

public List<Image> listNames(Image image) throws IllegalArgumentException, SQLException, ClassNotFoundException { 

    Connection connection = null; 
    PreparedStatement preparedStatement = null; 
    ResultSet resultset = null; 
    Database database = new Database(); 
    List<Image> list = new ArrayList<Image>(); 

    try { 

     connection = database.openConnection(); 
     preparedStatement = connection.prepareStatement(SQL_GET_PHOTOID);     
     preparedStatement.setLong(1, image.getUserid()); 
     resultset = preparedStatement.executeQuery(); 

     while(resultset.next()) { 
      image.setPhotoid(resultset.getString(1)); 
      list.add(image); 
     } 

    } catch (SQLException e) { 
     throw new SQLException(e); 
    } finally { 
     close(connection, preparedStatement, resultset); 
    } 
    return list; 
} 
+0

,您可以验证您的DAO返回的列表中有正确的ID? –

+0

代码看起来不错。在第一个servlet中,检查列表的5个元素是否包含不同的photoid。检查生成的HTML验证的img标签的src属性是不同的,匹配列表photoids。然后检查第二个servlet是否没有使其始终返回相同图像的错误。最后检查它返回的5张图像确实是不同的图像。 –

+0

实际上,我用输入文本框测试了这一点,打印出哪个ID正在返回,它只显示一个PhotoID,但它正确迭代了五次,因为该用户在数据库中有五张照片。 –

回答

1

当您遍历结果集,您正在设置在同一图像对象的带照片的身份证一遍又一遍......然后重新插入相同的对象添加到列表多次。

更新:简而言之,您的逻辑模型在该方法中存在缺陷。你不需要图像参数。像这样的东西应该工作(重点是建立在每个迭代一个新的Image对象):

List<Image> list = new ArrayList<Image>(); 
try { 
    ... 
    while(resultset.next()) { 
     Image image = new Image(); 
     image.setPhotoid(resultset.getString(1)); 
     list.add(image); 

,然后列表将有几个不同的对象。

+0

那该怎么样?你能给我一些代码吗?这可能会有所帮助。 –

+0

这是可行的。谢谢!! –