如何检索存储在散列映射中的单个数组值?

时间:2016-01-01 04:50:29

标签: servlets arraylist

我正在尝试使用Java Servlet编写购物车应用程序,但在尝试检索要在html页面中显示的单个项目时遇到困难。

以下是购物车订单项的摘要:

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;
       }
 }

以下是主推车类的摘录:

//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);
       }
  }

我不太确定使用hashmap是一个不错的选择,但ArrayList可能是更好的选择。无论哪种方式,我都被困在如何通过hashmap / arraylist迭代和检索单个项目。

以下是实现购物车的Servlet代码片段:

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>");
    ....
    ....
   }

我真正想要的是能够引用Item对象的各个项目。有关如何实现这一点的任何建议?或者有关如何编写更好更简单的购物车的任何建议?我当然希望能够参考对象的各个项目,以便我可以方便地操作它们。谢谢。

0 个答案:

没有答案