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.Arrays;
19  import java.util.Collections;
20  import java.util.List;
21  
22  import javax.servlet.http.HttpSession;
23  
24  import org.mybatis.jpetstore.domain.Cart;
25  import org.mybatis.jpetstore.domain.Order;
26  import org.mybatis.jpetstore.service.OrderService;
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.ModelAttribute;
32  import org.springframework.web.bind.annotation.PostMapping;
33  import org.springframework.web.bind.annotation.RequestMapping;
34  import org.springframework.web.bind.annotation.RequestParam;
35  
36  /**
37   * The Class OrderController.
38   */
39  @Controller
40  @RequestMapping("/order")
41  public class OrderController {
42  
43    /** The new order view. */
44    private static final String NEW_ORDER_VIEW = "order/NewOrderForm";
45    /** The shipping view. */
46    private static final String SHIPPING_VIEW = "order/ShippingForm";
47    /** The confirm view. */
48    private static final String CONFIRM_VIEW = "order/ConfirmOrder";
49    /** The view order view. */
50    private static final String VIEW_ORDER_VIEW = "order/ViewOrder";
51    /** The list orders view. */
52    private static final String LIST_ORDERS_VIEW = "order/ListOrders";
53    /** The error view. */
54    private static final String ERROR_VIEW = "common/Error";
55  
56    /** The card type list. */
57    private static final List<String> CARD_TYPE_LIST = Collections
58        .unmodifiableList(Arrays.asList("Visa", "MasterCard", "American Express"));
59  
60    /** The order service. */
61    @Autowired
62    private OrderService orderService;
63  
64    /**
65     * List orders.
66     *
67     * @param session
68     *          the session
69     * @param model
70     *          the model
71     *
72     * @return the string
73     */
74    @GetMapping("/list")
75    public String listOrders(HttpSession session, Model model) {
76      AccountController.AccountSession accountSession = (AccountController.AccountSession) session
77          .getAttribute("accountBean");
78      if (accountSession == null || !accountSession.isAuthenticated()) {
79        model.addAttribute("message",
80            "You must sign on before attempting to check out. Please sign on and try checking out again.");
81        return ERROR_VIEW;
82      }
83      List<Order> orderList = orderService.getOrdersByUsername(accountSession.getAccount().getUsername());
84      model.addAttribute("orderList", orderList);
85      return LIST_ORDERS_VIEW;
86    }
87  
88    /**
89     * New order form.
90     *
91     * @param session
92     *          the session
93     * @param model
94     *          the model
95     *
96     * @return the string
97     */
98    @GetMapping("/new")
99    public String newOrderForm(HttpSession session, Model model) {
100     AccountController.AccountSession accountSession = (AccountController.AccountSession) session
101         .getAttribute("accountBean");
102     Cart cart = (Cart) session.getAttribute("cart");
103 
104     if (accountSession == null || !accountSession.isAuthenticated()) {
105       model.addAttribute("message",
106           "You must sign on before attempting to check out. Please sign on and try checking out again.");
107       return "redirect:/account";
108     }
109     if (cart != null) {
110       Order order = new Order();
111       order.initOrder(accountSession.getAccount(), cart);
112       session.setAttribute("order", order);
113       model.addAttribute("order", order);
114       model.addAttribute("creditCardTypes", CARD_TYPE_LIST);
115       return NEW_ORDER_VIEW;
116     }
117     model.addAttribute("message", "An order could not be created because a cart could not be found.");
118     return ERROR_VIEW;
119   }
120 
121   /**
122    * New order.
123    *
124    * @param order
125    *          the order
126    * @param shippingAddressRequired
127    *          the shipping address required
128    * @param confirmed
129    *          the confirmed
130    * @param session
131    *          the session
132    * @param model
133    *          the model
134    *
135    * @return the string
136    */
137   @PostMapping("/new")
138   public String newOrder(@ModelAttribute Order order,
139       @RequestParam(value = "shippingAddressRequired", defaultValue = "false") boolean shippingAddressRequired,
140       @RequestParam(value = "confirmed", defaultValue = "false") boolean confirmed, HttpSession session, Model model) {
141 
142     Order sessionOrder = (Order) session.getAttribute("order");
143 
144     // When confirming, use the session order directly - the confirm form only
145     // submits confirmed=true with no other fields, so @ModelAttribute Order is empty
146     if (confirmed) {
147       if (sessionOrder != null) {
148         orderService.insertOrder(sessionOrder);
149         session.setAttribute("cart", new Cart());
150         model.addAttribute("message", "Thank you, your order has been submitted.");
151         model.addAttribute("order", sessionOrder);
152         return VIEW_ORDER_VIEW;
153       } else {
154         model.addAttribute("message", "An error occurred processing your order (order was null).");
155         return ERROR_VIEW;
156       }
157     }
158 
159     if (sessionOrder != null) {
160       // Only overwrite fields that were actually submitted (non-null).
161       // ShippingForm only posts ship fields; NewOrderForm only posts billing/payment fields.
162       // Unconditional setters would null-out whichever set is absent from the current form.
163       if (order.getCardType() != null)
164         sessionOrder.setCardType(order.getCardType());
165       if (order.getCreditCard() != null)
166         sessionOrder.setCreditCard(order.getCreditCard());
167       if (order.getExpiryDate() != null)
168         sessionOrder.setExpiryDate(order.getExpiryDate());
169       if (order.getBillToFirstName() != null)
170         sessionOrder.setBillToFirstName(order.getBillToFirstName());
171       if (order.getBillToLastName() != null)
172         sessionOrder.setBillToLastName(order.getBillToLastName());
173       if (order.getBillAddress1() != null)
174         sessionOrder.setBillAddress1(order.getBillAddress1());
175       if (order.getBillAddress2() != null)
176         sessionOrder.setBillAddress2(order.getBillAddress2());
177       if (order.getBillCity() != null)
178         sessionOrder.setBillCity(order.getBillCity());
179       if (order.getBillState() != null)
180         sessionOrder.setBillState(order.getBillState());
181       if (order.getBillZip() != null)
182         sessionOrder.setBillZip(order.getBillZip());
183       if (order.getBillCountry() != null)
184         sessionOrder.setBillCountry(order.getBillCountry());
185       if (order.getShipToFirstName() != null) {
186         sessionOrder.setShipToFirstName(order.getShipToFirstName());
187         sessionOrder.setShipToLastName(order.getShipToLastName());
188         sessionOrder.setShipAddress1(order.getShipAddress1());
189         sessionOrder.setShipAddress2(order.getShipAddress2());
190         sessionOrder.setShipCity(order.getShipCity());
191         sessionOrder.setShipState(order.getShipState());
192         sessionOrder.setShipZip(order.getShipZip());
193         sessionOrder.setShipCountry(order.getShipCountry());
194       }
195       order = sessionOrder;
196     }
197 
198     if (shippingAddressRequired) {
199       session.setAttribute("order", order);
200       model.addAttribute("order", order);
201       return SHIPPING_VIEW;
202     } else {
203       session.setAttribute("order", order);
204       model.addAttribute("order", order);
205       return CONFIRM_VIEW;
206     }
207   }
208 
209   /**
210    * View order.
211    *
212    * @param orderId
213    *          the order id
214    * @param session
215    *          the session
216    * @param model
217    *          the model
218    *
219    * @return the string
220    */
221   @GetMapping("/view")
222   public String viewOrder(@RequestParam("orderId") int orderId, HttpSession session, Model model) {
223     AccountController.AccountSession accountSession = (AccountController.AccountSession) session
224         .getAttribute("accountBean");
225     if (accountSession == null || !accountSession.isAuthenticated()) {
226       return "redirect:/account";
227     }
228     Order order = orderService.getOrder(orderId);
229     if (accountSession.getAccount().getUsername().equals(order.getUsername())) {
230       model.addAttribute("order", order);
231       return VIEW_ORDER_VIEW;
232     } else {
233       model.addAttribute("message", "You may only view your own orders.");
234       return ERROR_VIEW;
235     }
236   }
237 
238 }