只有数据库的最后一行在jsp页面中重复显示

时间:2014-05-09 17:02:34

标签: java

这是家庭servlet在jsp(java服务器页面)中显示数据列表。我无法显示数据库表行,而不是数据库的最后一行重复显示到数据库总数行。

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String address = "balaju";
    request.setAttribute("address", address);//response can not use

    //ItemBean item = new ItemBean();

    List<ItemBean> itemList = new ArrayList<ItemBean>();
    try {
        System.out.println("at home servlet");
        ItemDao dao = ItemDaoFactory.getItemDao();
        itemList = dao.getItemFromdb();
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("@home servlet ");
    for(ItemBean item1:itemList){
        System.out.println(item1.getTransactionTime());
        System.out.println(item1.getItemPrice());
        System.out.println(item1.getItemName());
    }
    request.setAttribute("itemList", itemList);
    RequestDispatcher rd = request.getRequestDispatcher("home/home.jsp");
    rd.forward(request, response);}

// jdbc代码打算显示数据表单数据库,但只有最后一行数据库使用jstl foreach标记显示在jsp页面中

 public List<ItemBean> getItemFromdb() throws SQLException {
    JdbcConnection connecton = new JdbcConnection();
    String query = "select * from itemsinfo";
    //Connection con = connecton.getConnection();
    List<ItemBean> itemList = new ArrayList<ItemBean>();
    ItemBean item = new ItemBean();
    Statement statement = connecton.getSqlStatement();
    ResultSet rs;
    try {
       rs = statement.executeQuery(query);
         while (rs.next()) {


            item.setItemName(rs.getString("itemname"));
            item.setItemPrice(rs.getDouble("itemprice"));
            item.setTransactionTime(rs.getString("transactiontime"));
           // itemList.add(item);

           /* System.out.println("itemname :"+item.getItemName());
            System.out.println("price:"+item.getItemPrice());
            System.out.println("time:"+item.getTransactionTime());
            System.out.println("/n"); */

        }

        System.out.println("at jdbc code");
        for(ItemBean item1:itemList){

            System.out.println(item1.getItemName());
            System.out.println(item1.getItemPrice());
            System.out.println(item1.getTransactionTime());
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }
    return itemList;

}

1 个答案:

答案 0 :(得分:2)

您的列表中只有一个项目。

 // ItemBean item = new ItemBean(); // You don't need this one.
 while (rs.next()) {
   ItemBean item = new ItemBean(); // Instantiate a new ItemBean, don't update ONE.
   item.setItemName(rs.getString("itemname"));
   item.setItemPrice(rs.getDouble("itemprice"));
   item.setTransactionTime(rs.getString("transactiontime"));
   itemList.add(item); // Add the item to the List.
 }