在jsp中显示迭代器

时间:2010-11-15 05:33:12

标签: jsp iterator

我有以下代码:

@Override  
public Iterator retrieve() throws SQLException {  
    List<PasalBean> pasalObject = new ArrayList<PasalBean>();  
    try {  
        Class.forName(dbDriver); 
        con = DriverManager.getConnection(url);  
        ps = con.createStatement();  
        rs = ps.executeQuery("select * from T_PASAL WHERE ID_PASAL = '" + id_pasal + "' ORDER BY ID_PASAL");  
        while (rs.next()) {  
            pasalObject.add(new  PasalBean(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4)));  
        }  
    }catch (Exception e) {  
        System.out.println("Error Data : " + e.getMessage());  
    }  
    return (Iterator) pasalObject;  
}

如何在JSP中显示它?

1 个答案:

答案 0 :(得分:1)

首先,此代码将失败。您无法将List转换为Iterator。让它返回List

然后,为了在servlet中显示它,你需要的是:

request.setAttribute("list", retrieve());
request.getRequestDispatcher("/path/to/jsp").forward();

然后在JSP中:

<c:forEach items="${list}" var="item">
   ${item.somePropertyOfTheBean}
</c:forEach>

最好将retrieve()方法放在单独的数据访问类(DAO)中,而不是直接放在servlet中。