test

Форк
0
Форк от lirfrnk/test
/
CartServlet.java 
125 строк · 5.8 Кб
1
package servlets;
2

3
import java.io.IOException;
4
import java.io.PrintWriter;
5
import java.util.ArrayList;
6
import java.util.List;
7

8
import javax.servlet.RequestDispatcher;
9
import javax.servlet.ServletException;
10
import javax.servlet.http.HttpServlet;
11
import javax.servlet.http.HttpServletRequest;
12
import javax.servlet.http.HttpServletResponse;
13
import javax.servlet.http.HttpSession;
14

15
import com.bittercode.constant.BookStoreConstants;
16
import com.bittercode.model.Book;
17
import com.bittercode.model.Cart;
18
import com.bittercode.model.UserRole;
19
import com.bittercode.service.BookService;
20
import com.bittercode.service.impl.BookServiceImpl;
21
import com.bittercode.util.StoreUtil;
22

23
public class CartServlet extends HttpServlet {
24

25
    BookService bookService = new BookServiceImpl();
26

27
    public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
28
        PrintWriter pw = res.getWriter();
29
        res.setContentType(BookStoreConstants.CONTENT_TYPE_TEXT_HTML);
30

31
        // Check if Customer is logged In
32
        if (!StoreUtil.isLoggedIn(UserRole.CUSTOMER, req.getSession())) {
33
            RequestDispatcher rd = req.getRequestDispatcher("CustomerLogin.html");
34
            rd.include(req, res);
35
            pw.println("<table class=\"tab\"><tr><td>Please Login First to Continue!!</td></tr></table>");
36
            return;
37
        }
38
        try {
39
            // Add/Remove Item from the cart if requested
40
            // store the comma separated bookIds of cart in the session
41
            StoreUtil.updateCartItems(req);
42

43
            HttpSession session = req.getSession();
44
            String bookIds = "";
45
            if (session.getAttribute("items") != null)
46
                bookIds = (String) session.getAttribute("items");// read comma separated bookIds from session
47

48
            RequestDispatcher rd = req.getRequestDispatcher("CustomerHome.html");
49
            rd.include(req, res);
50

51
            // Set the active tab as cart
52
            StoreUtil.setActiveTab(pw, "cart");
53

54
            // Read the books from the database with the respective bookIds
55
            List<Book> books = bookService.getBooksByCommaSeperatedBookIds(bookIds);
56
            List<Cart> cartItems = new ArrayList<Cart>();
57
            pw.println("<div id='topmid' style='background-color:grey'>Shopping Cart</div>");
58
            pw.println("<table class=\"table table-hover\" style='background-color:white'>\r\n"
59
                    + "  <thead>\r\n"
60
                    + "    <tr style='background-color:black; color:white;'>\r\n"
61
                    + "      <th scope=\"col\">BookId</th>\r\n"
62
                    + "      <th scope=\"col\">Name</th>\r\n"
63
                    + "      <th scope=\"col\">Author</th>\r\n"
64
                    + "      <th scope=\"col\">Price/Item</th>\r\n"
65
                    + "      <th scope=\"col\">Quantity</th>\r\n"
66
                    + "      <th scope=\"col\">Amount</th>\r\n"
67
                    + "    </tr>\r\n"
68
                    + "  </thead>\r\n"
69
                    + "  <tbody>\r\n");
70
            double amountToPay = 0;
71
            if (books == null || books.size() == 0) {
72
                pw.println("    <tr style='background-color:green'>\r\n"
73
                        + "      <th scope=\"row\" colspan='6' style='color:yellow; text-align:center;'> No Items In the Cart </th>\r\n"
74
                        + "    </tr>\r\n");
75
            }
76
            for (Book book : books) {
77
                int qty = (int) session.getAttribute("qty_" + book.getBarcode());
78
                Cart cart = new Cart(book, qty);
79
                cartItems.add(cart);
80
                amountToPay += (qty * book.getPrice());
81
                pw.println(getRowData(cart));
82
            }
83

84
            // set cartItems and amountToPay in the session
85
            session.setAttribute("cartItems", cartItems);
86
            session.setAttribute("amountToPay", amountToPay);
87

88
            if (amountToPay > 0) {
89
                pw.println("    <tr style='background-color:green'>\r\n"
90
                        + "      <th scope=\"row\" colspan='5' style='color:yellow; text-align:center;'> Total Amount To Pay </th>\r\n"
91
                        + "      <td colspan='1' style='color:white; font-weight:bold'><span>&#8377;</span> "
92
                        + amountToPay
93
                        + "</td>\r\n"
94
                        + "    </tr>\r\n");
95
            }
96
            pw.println("  </tbody>\r\n"
97
                    + "</table>");
98
            if (amountToPay > 0) {
99
                pw.println("<div style='text-align:right; margin-right:20px;'>\r\n"
100
                        + "<form action=\"checkout\" method=\"post\">"
101
                        + "<input type='submit' class=\"btn btn-primary\" name='pay' value='Proceed to Pay &#8377; "
102
                        + amountToPay + "'/></form>"
103
                        + "    </div>");
104
            }
105
        } catch (Exception e) {
106
            e.printStackTrace();
107
        }
108
    }
109

110
    public String getRowData(Cart cart) {
111
        Book book = cart.getBook();
112
        return "    <tr>\r\n"
113
                + "      <th scope=\"row\">" + book.getBarcode() + "</th>\r\n"
114
                + "      <td>" + book.getName() + "</td>\r\n"
115
                + "      <td>" + book.getAuthor() + "</td>\r\n"
116
                + "      <td><span>&#8377;</span> " + book.getPrice() + "</td>\r\n"
117
                + "      <td><form method='post' action='cart'><button type='submit' name='removeFromCart' class=\"glyphicon glyphicon-minus btn btn-danger\"></button> "
118
                + "<input type='hidden' name='selectedBookId' value='" + book.getBarcode() + "'/>"
119
                + cart.getQuantity()
120
                + " <button type='submit' name='addToCart' class=\"glyphicon glyphicon-plus btn btn-success\"></button></form></td>\r\n"
121
                + "      <td><span>&#8377;</span> " + (book.getPrice() * cart.getQuantity()) + "</td>\r\n"
122
                + "    </tr>\r\n";
123
    }
124

125
}
126

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.