3

当我第一次在服务器上运行 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);
}

这是购物车类:

私有 ConcurrentHashMap 项;

/** 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);
}
4

2 回答 2

1

如果这里抛出异常......

    cart.addItem(pr);

...那是因为cartnull。最可能的解释是这个调用返回null

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

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

于 2012-05-12T09:22:28.350 回答
0

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

于 2012-05-12T08:58:56.183 回答