View Javadoc
1   /*
2    *    Copyright 2010-2026 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       https://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package org.mybatis.jpetstore.web.controllers;
17  
18  import java.util.Iterator;
19  
20  import javax.servlet.http.HttpServletRequest;
21  import javax.servlet.http.HttpSession;
22  
23  import org.mybatis.jpetstore.domain.Cart;
24  import org.mybatis.jpetstore.domain.CartItem;
25  import org.mybatis.jpetstore.domain.Item;
26  import org.mybatis.jpetstore.service.CatalogService;
27  import org.springframework.beans.factory.annotation.Autowired;
28  import org.springframework.stereotype.Controller;
29  import org.springframework.ui.Model;
30  import org.springframework.web.bind.annotation.GetMapping;
31  import org.springframework.web.bind.annotation.PostMapping;
32  import org.springframework.web.bind.annotation.RequestMapping;
33  import org.springframework.web.bind.annotation.RequestParam;
34  
35  /**
36   * The Class CartController.
37   */
38  @Controller
39  @RequestMapping("/cart")
40  public class CartController {
41  
42    /** The error view. */
43    private static final String ERROR_VIEW = "common/Error";
44  
45    /** The catalog service. */
46    @Autowired
47    private CatalogService catalogService;
48  
49    /**
50     * Get cart.
51     *
52     * @param session
53     *          the session
54     *
55     * @return the cart
56     */
57    private Cart getCart(HttpSession session) {
58      Cart cart = (Cart) session.getAttribute("cart");
59      if (cart == null) {
60        cart = new Cart();
61        session.setAttribute("cart", cart);
62      }
63      return cart;
64    }
65  
66    /**
67     * View cart.
68     *
69     * @param session
70     *          the session
71     * @param model
72     *          the model
73     *
74     * @return the string
75     */
76    @GetMapping({ "", "/" })
77    public String viewCart(HttpSession session, Model model) {
78      model.addAttribute("cart", getCart(session));
79      return "cart/Cart";
80    }
81  
82    /**
83     * Add item to cart.
84     *
85     * @param workingItemId
86     *          the working item id
87     * @param session
88     *          the session
89     * @param model
90     *          the model
91     *
92     * @return the string
93     */
94    @GetMapping("/addItem")
95    public String addItemToCart(@RequestParam(value = "workingItemId", required = false) String workingItemId,
96        HttpSession session, Model model) {
97      if (workingItemId == null || workingItemId.trim().isEmpty()) {
98        model.addAttribute("message", "Invalid item ID: cannot add item to cart.");
99        return ERROR_VIEW;
100     }
101     Cart cart = getCart(session);
102     if (cart.containsItemId(workingItemId)) {
103       cart.incrementQuantityByItemId(workingItemId);
104     } else {
105       boolean isInStock = catalogService.isItemInStock(workingItemId);
106       Item item = catalogService.getItem(workingItemId);
107       cart.addItem(item, isInStock);
108     }
109     model.addAttribute("cart", cart);
110     return "cart/Cart";
111   }
112 
113   /**
114    * Remove item from cart.
115    *
116    * @param workingItemId
117    *          the working item id
118    * @param session
119    *          the session
120    * @param model
121    *          the model
122    *
123    * @return the string
124    */
125   @GetMapping("/removeItem")
126   public String removeItemFromCart(@RequestParam(value = "workingItemId", required = false) String workingItemId,
127       HttpSession session, Model model) {
128     if (workingItemId == null || workingItemId.trim().isEmpty()) {
129       model.addAttribute("message", "Invalid item ID: cannot remove item from cart.");
130       return ERROR_VIEW;
131     }
132     Cart cart = getCart(session);
133     Item item = cart.removeItemById(workingItemId);
134     if (item == null) {
135       model.addAttribute("message", "Attempted to remove null CartItem from Cart.");
136       return ERROR_VIEW;
137     }
138     model.addAttribute("cart", cart);
139     return "cart/Cart";
140   }
141 
142   /**
143    * Update cart quantities.
144    *
145    * @param request
146    *          the request
147    * @param session
148    *          the session
149    * @param model
150    *          the model
151    *
152    * @return the string
153    */
154   @PostMapping("/update")
155   public String updateCartQuantities(HttpServletRequest request, HttpSession session, Model model) {
156     Cart cart = getCart(session);
157     Iterator<CartItem> cartItems = cart.getAllCartItems();
158     while (cartItems.hasNext()) {
159       CartItem cartItem = cartItems.next();
160       String itemId = cartItem.getItem().getItemId();
161       try {
162         int quantity = Integer.parseInt(request.getParameter(itemId));
163         cart.setQuantityByItemId(itemId, quantity);
164         if (quantity < 1) {
165           cartItems.remove();
166         }
167       } catch (NumberFormatException e) {
168         // ignore invalid numeric input on purpose
169       }
170     }
171     model.addAttribute("cart", cart);
172     return "cart/Cart";
173   }
174 
175   /**
176    * Check out.
177    *
178    * @param session
179    *          the session
180    * @param model
181    *          the model
182    *
183    * @return the string
184    */
185   @GetMapping("/checkout")
186   public String checkOut(HttpSession session, Model model) {
187     model.addAttribute("cart", getCart(session));
188     return "cart/Checkout";
189   }
190 
191 }