3

サーバーで初めて Java サーブレットを実行すると、すべての Web ページが正常に動作し、問題はありません。しかし、サーバーを停止して再起動し、サーブレットを再度実行すると、1 つのページにヌル ポインター例外が発生します。このエラーが発生した場所で何かを印刷しようとしましたが、System.out.printl("something")そこに書き込んでサーブレットを再度実行すると(サーバーを何度も再起動すると)、例外がスローされなくなります。

誰でもこの問題を解決するのを助けることができますか?

これは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);

...それはcartですnull。最も可能性の高い説明は、この呼び出しがを返すことnullです。

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

セッションには(まだ)"Cart"エントリが含まれていないため、これが発生します。あなたがする必要があるのは、その呼び出しの結果をテストすることです。が返された場合はnull、新しい ShoppingCartオブジェクトを作成し、 `Session.setAttribute(...)を使用して、セッションを使用する次のリクエストのセッションオブジェクトに追加する必要があります。

于 2012-05-12T09:22:28.350 に答える
0

再起動すると、null ポインターの原因となっているフォームを再送信していると思います。これは、セッションを取得しようとしたとき、または Cart 属性を取得したときに発生しています。cart.addItem を呼び出すと、cart オブジェクトは null になります。

于 2012-05-12T08:58:56.183 に答える