When I run the Java servlet for the first time on the server, all the web pages work fine and there are no problems. But when I stop the server, restart it and start the servlet again, there is a null pointer exception on one page. I tried to print something where this error occurred, but when I write System.out.printl("something")there and run the servlet again (rebooting the server many times), a throw no longer occurs.
Does anyone help solve this problem?
Here is the doPost method where the exception is thrown
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);
}
RequestDispatcher dispatch = request.getRequestDispatcher("shopping-cart.jsp");
dispatch.forward(request, response);
}
and here is the basket class:
ConcurrentHashMap personal items
public ShoppingCart(){
items = new ConcurrentHashMap<Product, Integer>();
}
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);
}
}
public void updateItem(Product pr, int quantity){
if(quantity == 0)items.remove(pr);
else items.put(pr, quantity);
}
public Iterator<Product> cartItems(){
return items.keySet().iterator();
}
public int getQuantity(Product pr){
return items.get(pr);
}
source
share