Java 服务器上的 Web 编程,空指针异常



当我第一次在服务器上运行Java servlet时,所有网页都运行良好,没有问题。但是当我停止服务器,重新启动它并再次运行servlet时,一个页面上出现空指针异常。我试图打印一些东西,发生此错误的地方,但是当我在那里写System.out.printl("something"),然后再次运行servlet(多次重新启动服务器)时,没有更多的异常。

任何人都可以帮助解决这个问题吗?

这是 doPost 方法,其中抛出异常

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ShoppingCart cart = (ShoppingCart)request.getSession().getAttribute("Cart");
    ProductCatalog pc = (ProductCatalog) request.getServletContext().getAttribute("Product Catalog");
    String id = request.getParameter("productID");
    if(id != null){
        Product pr = pc.getProduct(id);
        cart.addItem(pr); // here is null pointer exception
    }
    RequestDispatcher dispatch = request.getRequestDispatcher("shopping-cart.jsp");
    dispatch.forward(request, response);
}

这是购物车类:

私有的并发哈希图项;

/** Creates new Shopping Cart */
public ShoppingCart(){
    items = new ConcurrentHashMap<Product, Integer>();
}
/** Adds a product having this id into cart and increases quantity. */
//This method is called after "add to cart" button is clicked. 
public void addItem(Product pr){
    System.out.println(pr.getId() + " sahdhsaihdasihdasihs");
    if(items.containsKey(pr)){
        int quantity = items.get(pr) + 1;
        items.put(pr, quantity);
    } else {
        items.put(pr, 1);
    }
}
/** 
 * Adds a product having this id into cart and 
 * increases quantity with the specified number. 
 * If quantity is zero, we remove this product from cart.
 */
//This method is called many times after "update cart" button is clicked. 
public void updateItem(Product pr, int quantity){
    if(quantity == 0)items.remove(pr);
    else items.put(pr, quantity);
}
/** Cart iterator */
public Iterator<Product> cartItems(){
    return items.keySet().iterator();
}
/** Returns quantity of this product */
public int getQuantity(Product pr){
    return items.get(pr);
}

如果在此处抛出异常...

    cart.addItem(pr);

。那是因为cart null. 最可能的解释是此调用返回null

    request.getSession().getAttribute("Cart");

发生这种情况是因为会话(尚)不包含"Cart"条目。 您需要做的是测试该调用的结果。 如果它返回 null ,则需要创建一个新的 ShoppingCart对象,并使用 'Session.setAttribute(...) 将其添加到使用该会话的下一个请求的会话对象中。

当您重新启动时,我猜您正在重新提交导致空指针的表单,当您尝试检索会话或获取 Cart 属性时,都会发生这种情况。当您调用 cart.addItem 时,cart 对象为空。

最新更新