【问题标题】:How to add more shopping cart not increment quantity when refresh page in spring mvc hibernatespring mvc hibernate中刷新页面时如何添加更多购物车而不增加数量
【发布时间】:2015-11-17 03:47:07
【问题描述】:

我在 spring mvc 中创建购物车。我可以使用以下功能添加购物车并添加继续购物车:

@RequestMapping(value = "/ordernow", method = RequestMethod.POST)
public String ordernow(@ModelAttribute("product") Product product, HttpSession session) {

    if (session.getAttribute("cart") == null) {
        List<Item> cart = new ArrayList<Item>();
        cart.add(new Item(this.pm.find(product.getId()), 1));
        session.setAttribute("cart", cart);
    } else {
        List<Item> cart = (List<Item>) session.getAttribute("cart");
        boolean flag = false;
        for (Item item : cart) {
            if (item.getProduct().getId() == product.getId()) {
                item.setQuantity(item.getQuantity() + 1);
                flag = true;
                break;
            }
        }
        if (flag == false) {
            cart.add(new Item(this.pm.find(product.getId()), 1));
        }
    }
    return "cart";
}

当我刷新页面数量总是增加。我不想在刷新页面时增加数量。我想要增加数量,除非我点击按钮 AddToCart。 请帮帮我!

【问题讨论】:

    标签: java hibernate spring-mvc


    【解决方案1】:

    您应该将方法拆分为 2 个单独的方法。一种用于页面渲染,一种用于将商品添加到购物车。页面渲染方法(我们将其命名为 orderPage)应该返回“cart”视图,但 addItem 方法应该返回“redirect:orderPage”。

    因此,刷新调用 orderPage 并在购物车中添加任何内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-14
      • 1970-01-01
      • 1970-01-01
      • 2021-05-09
      相关资源
      最近更新 更多