简体   繁体   中英

How to add more shopping cart not increment quantity when refresh page in spring mvc hibernate

I create shopping cart in spring mvc . I can add shopping cart and add continue shopping cart using function like below :

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

When i refresh page quantity always increment.I don't want increment quantity when refresh page. I want increment quantity unless i click button AddToCart. Please help me!

You should split the method to have 2 separate ones. One for page rendering and one for adding item to cart. The page rendering method (let's name it orderPage) should return "cart" view but the addItem method should return "redirect:orderPage".

So refreshing calls the orderPage and add nothing to the cart.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM