有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我无法从充满Order对象的ArrayList打印

因此,当我试图从arraylist打印时,会出现空指针异常,我似乎无法理解为什么,因为我对编码还是相当陌生。请记住,我将列表存储为会话的一个属性,该属性是在您登录时创建的。下面是示例1,我在其中创建并尝试添加到列表中:

public static ArrayList<Order> getOrdersByUserId( int userid ) throws LoginSampleException {
    try {
        Connection con = Connector.connection();
        String SQL = "SELECT * FROM `order` "
                + "WHERE fk_userid=?";
        PreparedStatement ps = con.prepareStatement( SQL );
        ps.setInt( 1, userid );
        ResultSet rs = ps.executeQuery();
        ArrayList<Order> orders = new ArrayList<>();
        while ( rs.next() ) {
            Order order = new Order(rs.getInt("length"), rs.getInt("width"), rs.getInt("height"));
            orders.add(order);
        }
        return orders;
    } catch ( ClassNotFoundException | SQLException ex ) {
        throw new LoginSampleException(ex.getMessage());
    }
}

这是示例2,我将列表存储在会话中

public class ViewOrders extends Command {

@Override
String execute(HttpServletRequest request, HttpServletResponse response) throws LoginSampleException {
    ArrayList<Order> ol = new ArrayList();
    HttpSession session = request.getSession();
    if ( session.getAttribute("ordersByUserID") == null ) {
        User user = (User) session.getAttribute( "user" );
        ol = LogicFacade.getOrdersByUserID( user.getId() );
        System.out.println( "session not found" );
        request.getSession().setAttribute( "ordersByUserID", ol );
    } 
    return "vieworders";
}

}

下面是示例3,我尝试从中打印,得到NullPointerException:

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <table>
        <thead>
            <td>This is your previous orders</td>
        </thead>
        <tr>
            <td>
                <%
                    if (request.getSession().getAttribute("user") != null) { 
                        List<Order> orderlist = (List<Order>)request.getSession().getAttribute("ordersById");
                        for (int i = 0; i < orderlist.size(); i++) { %>
                            <a href="vieworderdetails.jsp?orderID=<%out.println(orderlist.get(i).getId());%>">
                                <%
                                    out.println(orderlist.get(i).getId());
                                %>
                            </a> <%
                        }
                    }
                %>       
            </td>
        </tr>
    </table>

</body>


共 (0) 个答案