Servlet arrayList返回null

时间:2017-10-12 19:42:19

标签: javascript java jsp http

我似乎面临的问题是我的对象arrayList保持返回null和我;我无法弄清楚原因。我的代码如下:

   <% ArrayList<Product> pList = new ArrayList<>();
            pList = (ArrayList<Product>) session.getAttribute("productList");
            for (int i = 0; i < pList.size(); i++) {%>
        <tr>
            <td><%pList.get(i).getProductID();%></td>
            <td><%pList.get(i).getManufacturer();%></td>
            <td><%pList.get(i).getItem();%></td>
            <td><%pList.get(i).getDescription();%></td>
            <td><%pList.get(i).getPrice();%></td>
            <td>
                <form action=<%=response.encodeURL("AddtoCartServlet.do")%> method="POST">
                      Quantity:<input type="text" name="quantity">
                    <input type="submit" value="Add to Cart"/>
                    <%--<input type="hidden" name="prodID" value=<%=product.getProductID();%>--%>
                </form>
            </td>
        </tr>

我的servlet的代码在这里:

     @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ProductDAO dao = new ProductDAO();
    ArrayList<Product> productList = dao.getAllProducts();
    HttpSession session = request.getSession();
    session.setAttribute("productList", productList);
    request.getRequestDispatcher("productList.jsp").forward(request, response);

}

最后,检索所有产品对象的代码在这里:

    public ArrayList<Product> getAllProducts() {
    ArrayList<Product> productList = new ArrayList();

    Connection conn = DBConnector.getConnection();
    PreparedStatement stmt = null;
    ResultSet rs = null;
    String sqlQuery = "SELECT * FROM Product";
    try {
        stmt = conn.prepareStatement(sqlQuery);
        rs = stmt.executeQuery();
        while (rs.next()) {
            Product prod = new Product();
            prod.setProductID(rs.getString("ProductId"));
            prod.setManufacturer(rs.getString("Manufacturer"));
            prod.setItem(rs.getString("Item"));
            prod.setDescription(rs.getString("Description"));
            prod.setPrice(rs.getDouble("Price"));
        }
    } catch (SQLException ex) {
        Logger.getLogger(ProductDAO.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println(ex.getErrorCode());
        System.out.println(ex.getSQLState());
        System.out.println(ex.getMessage());
    } finally {
        DBConnector.closeJDBCObjects(null, stmt, rs);
    }
    return productList;
}

0 个答案:

没有答案