Exemplo n.º 1
0
  /**
   * Handles the HTTP <code>POST</code> method.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String userPath = request.getServletPath();
    HttpSession session = request.getSession();
    ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
    Validator validator = new Validator();
    // if addToCart action is called
    if (userPath.equals("/addToCart")) {

      // if user is adding item to cart for first time
      // create cart object and attach it to user session
      if (cart == null) {

        cart = new ShoppingCart();
        session.setAttribute("cart", cart);
      }

      // get user input from request
      String productId = request.getParameter("productId");

      if (!productId.isEmpty()) {

        Product product = productFacade.find(Integer.parseInt(productId));
        cart.addItem(product);
      }

      userPath = "/category";

      // if updateCart action is called
    } else if (userPath.equals("/updateCart")) {

      // get input from request
      String productId = request.getParameter("productId");
      String quantity = request.getParameter("quantity");
      boolean invalidEntry = validator.validateQuantity(productId, quantity);

      if (!invalidEntry) {

        Product product = productFacade.find(Integer.parseInt(productId));
        cart.update(product, quantity);
      }
      userPath = "/cart";

      // if purchase action is called
    } else if (userPath.equals("/purchase")) {
      if (cart != null) {

        // extract user data from request
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        String cityRegion = request.getParameter("cityRegion");
        String ccNumber = request.getParameter("creditcard");
        // validate user data
        boolean validationErrorFlag = false;
        validationErrorFlag =
            validator.validateForm(name, email, phone, address, cityRegion, ccNumber, request);

        // if validation error found, return user to checkout
        if (validationErrorFlag == true) {
          request.setAttribute("validationErrorFlag", validationErrorFlag);
          userPath = "/checkout";

          // otherwise, save order to database
        } else {

          int orderId =
              orderManager.placeOrder(name, email, phone, address, cityRegion, ccNumber, cart);

          // if order processed successfully send user to confirmation page
          if (orderId != 0) {
            // in case language was set using toggle, get language choice before destroying session
            Locale locale =
                (Locale) session.getAttribute("javax.servlet.jsp.jstl.fmt.locale.session");
            String language = "";

            if (locale != null) {
              language = (String) locale.getLanguage();
            }

            // dissociate shopping cart from session
            cart = null;

            // end session
            session.invalidate();
            if (!language.isEmpty()) { // if user changed language using the toggle,
              // reset the language attribute - otherwise
              request.setAttribute(
                  "language", language); // language will be switched on confirmation page!
            }

            // get order details
            Map orderMap = orderManager.getOrderDetails(orderId);

            // place order details in request scope
            request.setAttribute("customer", orderMap.get("customer"));
            request.setAttribute("products", orderMap.get("products"));
            request.setAttribute("orderRecord", orderMap.get("orderRecord"));
            request.setAttribute("orderedProducts", orderMap.get("orderedProducts"));

            userPath = "/confirmation";

            // otherwise, send back to checkout page and display error
          } else {
            userPath = "/checkout";
            request.setAttribute("orderFailureFlag", true);
          }
        }
      }
    }
    // use RequestDispatcher to forward request internally
    String url = "/WEB-INF/view" + userPath + ".jsp";

    try {
      request.getRequestDispatcher(url).forward(request, response);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }