I'm creating a shopping cart using servlets. I've got a form in a .html file which send it to the post method of my servlet. Here's the form:
.HTML File
<form action="Sess04" method="post">
<label>
Nazwa:
<input type="text" name="name">
</label><br>
<label>
Ilość:
<input type="number" name="quantity" min="1">
</label><br>
<label>
Cena:
<input type="number" name="price" step="0.01" min="0">
</label><br>
<label>
<input type="submit" value="Dodaj do koszyka">
</label>
</form>
Here's my servlet (doPost method, doGet is empty for now):
HttpSession sess = request.getSession();
List<Item> itemsList = (List<Item>) sess.getAttribute("cart");
if (itemsList.isEmpty()) { ← Here NullPointException
itemsList = new ArrayList<>();
}
String name = request.getParameter("name");
int quantity = Integer.parseInt(request.getParameter("quantity"));
double price = Double.parseDouble(request.getParameter("price"));
Item item = new Item(name, quantity, price);
itemsList.add(item);
sess.setAttribute("cart", itemsList);
for (int i = 0; i <= itemsList.size(); i++) {
response.getWriter().append("Product " + i + " - " + quantity + " x " + " " + price + "USD" + " = " + quantity*price + "USD");
}
When I open the index in my browser, add the item and submit, it returns me the NullPointerException in the marked place (if). Why is that happening?