I am trying to write a shopping cart application using Java Servlet but got stuck when trying to retrieve individual items to display in html page.
Here is the snippet of the line item of the cart:
public class Item
{
private int id;
private String name;
private final int qty;
private final double price;
private final String description;
//constructor
public Item(int ident, String n, int q, double p, String desc)
{
this.id = ident;
this.name = n;
this.qty = q;
this.price = p;
this.description = desc;
}
}
Here is the snippet of the main cart class:
//main cart
public class Cart
{
HashMap<String, Item> cartItems;
public Cart()
{
cartItems = new Item();
}
public HashMap getCartItems()
{
return cartItems;
}
public void addToCart(String itemId, String itemName, int qty, double price, String desc)
{
Item product = new Item(itemId, itemName, qty, price, desc);
cartItems.put(itemId, product);
}
public void deleteFromCart(String itemId)
{
cartItems.remove(itemId);
}
}
I am not so sure using hashmap is a good choice but ArrayList maybe a better choice. Either way, I am stuck on how to iterate and retrieve individual items over hashmap/arraylist.
Here is a snippet of the Servlet code that implements the shopping cart:
String action = request.getParameter("action");
HttpSession session = request.getSession();
Cart shoppingCart;
shoppingCart = (Cart) session.getAttribute("cart");
if (shoppingCart == null)
{
shoppingCart = new Cart();
session.setAttribute("cart", shoppingCart);
}
switch (action)
{
case "add":
shoppingCart.addToCart(id, name, qty, price, desc);
session.setAttribute("cart", shoppingCart);
break;
case "delete":
shoppingCart.deleteFromCart(id);
session.setAttribute("cart", shoppingCart);
shoppingCart = (Cart) session.getAttribute("cart");
break;
}
HashMap<String, Item> items = shoppingCart.getCartItems();
if (items.size() > 0)
{
//cart is not empty ... iterate over the array and display to user
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Shopping Cart</title>");
....
....
}
What I really want is to be able to refer to the Item object's individual items. Any suggestion as to how to accomplish this? Or any suggestion on how to write a better and easier shopping cart? I definitely want to be able to refer to the object's individual items so that I can manipulate them conveniently.Thanks in advance.