Exemplo n.º 1
0
  /**
   * Handles the HTTP <code>GET</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 doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String userPath = request.getServletPath();
    HttpSession session = request.getSession();
    Category selectedCategory;
    Collection<Product> categoryProducts;

    // if category page is requested
    if (userPath.equals("/category")) {

      // get categoryId from request
      String categoryId = request.getQueryString();

      if (categoryId != null) {

        // get selected category
        selectedCategory = categoryFacade.find(Short.parseShort(categoryId));

        // place selected category in session scope
        session.setAttribute("selectedCategory", selectedCategory);

        // get all products for selected category
        categoryProducts = selectedCategory.getProductCollection();

        // place category products in session scope
        session.setAttribute("categoryProducts", categoryProducts);
      }

      // if cart page is requested
    } else if (userPath.equals("/viewCart")) {

      String clear = request.getParameter("clear");

      if ((clear != null) && clear.equals("true")) {

        ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
        cart.clear();
      }

      userPath = "/cart";

      // if checkout page is requested
    } else if (userPath.equals("/checkout")) {

      ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");

      // calculate total
      cart.calculateTotal(surcharge);

      // forward to checkout page and switch to a secure channel
      // if user switches language
    } else if (userPath.equals("/chooseLanguage")) {
      // get language choice
      String language = request.getParameter("language");
      // place in request scope
      request.setAttribute("language", language);
      String userView = (String) session.getAttribute("view");
      if ((userView != null)
          && (!userView.equals("/index"))) { // index.jsp exists outside 'view' folder
        // so must be forwarded separately
        userPath = userView;
      } else {
        // if previous view is index or cannot be determined, send user to welcome page
        try {
          request.getRequestDispatcher("/index.jsp").forward(request, response);
        } catch (Exception ex) {
          ex.printStackTrace();
        }
        return;
      }
    }

    // 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();
    }
  }