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