test

Форк
0
Форк от lirfrnk/test
/
ViewBookServlet.java 
144 строки · 6.8 Кб
1
package servlets;
2

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

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

14
import com.bittercode.model.Book;
15
import com.bittercode.model.UserRole;
16
import com.bittercode.service.BookService;
17
import com.bittercode.service.impl.BookServiceImpl;
18
import com.bittercode.util.StoreUtil;
19

20
public class ViewBookServlet extends HttpServlet {
21

22
    // book service for database operations and logics
23
    BookService bookService = new BookServiceImpl();
24

25
    public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
26
        PrintWriter pw = res.getWriter();
27
        res.setContentType("text/html");
28

29
        // Check if the customer is logged in, or else return to login page
30
        if (!StoreUtil.isLoggedIn(UserRole.CUSTOMER, req.getSession())) {
31
            RequestDispatcher rd = req.getRequestDispatcher("CustomerLogin.html");
32
            rd.include(req, res);
33
            pw.println("<table class=\"tab\"><tr><td>Please Login First to Continue!!</td></tr></table>");
34
            return;
35
        }
36
        try {
37

38
            // Read All available books from the database
39
            List<Book> books = bookService.getAllBooks();
40

41
            // Default Page to load data into
42
            RequestDispatcher rd = req.getRequestDispatcher("CustomerHome.html");
43
            rd.include(req, res);
44

45
            // Set Available Books tab as active
46
            StoreUtil.setActiveTab(pw, "books");
47

48
            // Show the heading for the page
49
            pw.println("<div id='topmid' style='background-color:grey'>Available Books"
50
                    + "<form action=\"cart\" method=\"post\" style='float:right; margin-right:20px'>"
51
                    + "<input type='submit' class=\"btn btn-primary\" name='cart' value='Proceed'/></form>"
52
                    + "</div>");
53
            pw.println("<div class=\"container\">\r\n"
54
                    + "        <div class=\"card-columns\">");
55

56
            // Add or Remove items from the cart, if requested
57
            StoreUtil.updateCartItems(req);
58

59
            HttpSession session = req.getSession();
60
            for (Book book : books) {
61

62
                // Add each book to display as a card
63
                pw.println(this.addBookToCard(session, book));
64

65
            }
66

67
            // Checkout Button
68
            pw.println("</div>"
69
                    + "<div style='float:auto'><form action=\"cart\" method=\"post\">"
70
                    + "<input type='submit' class=\"btn btn-success\" name='cart' value='Proceed to Checkout'/></form>"
71
                    + "    </div>");
72

73
        } catch (Exception e) {
74
            e.printStackTrace();
75
        }
76
    }
77

78
    public String addBookToCard(HttpSession session, Book book) {
79
        String bCode = book.getBarcode();
80
        int bQty = book.getQuantity();
81

82
        // Quantity of the current book added to the cart
83
        int cartItemQty = 0;
84
        if (session.getAttribute("qty_" + bCode) != null) {
85
            // Quantity of each book in the cart will be added in the session prefixed with
86
            // 'qty_' following with bookId
87
            cartItemQty = (int) session.getAttribute("qty_" + bCode);
88
        }
89

90
        // Button To Add/Remove item from the cart
91
        String button = "";
92
        if (bQty > 0) {
93
            // If no items in the cart, show add to cart button
94
            // If items is added to the cart, then show +, - button to add/remove more items
95
            button = "<form action=\"viewbook\" method=\"post\">"
96
                    + "<input type='hidden' name = 'selectedBookId' value = " + bCode + ">"
97
                    + "<input type='hidden' name='qty_" + bCode + "' value='1'/>"
98
                    + (cartItemQty == 0
99
                            ? "<input type='submit' class=\"btn btn-primary\" name='addToCart' value='Add To Cart'/></form>"
100
                            : "<form method='post' action='cart'>"
101
                                    + "<button type='submit' name='removeFromCart' class=\"glyphicon glyphicon-minus btn btn-danger\"></button> "
102
                                    + "<input type='hidden' name='selectedBookId' value='" + bCode + "'/>"
103
                                    + cartItemQty
104
                                    + " <button type='submit' name='addToCart' class=\"glyphicon glyphicon-plus btn btn-success\"></button></form>")
105
                    + "";
106
        } else {
107
            // If available Quantity is zero, show out of stock button
108
            button = "<p class=\"btn btn-danger\">Out Of Stock</p>\r\n";
109
        }
110

111
        // Bootstrap card to show the book data
112
        return "<div class=\"card\">\r\n"
113
                + "                <div class=\"row card-body\">\r\n"
114
                + "                    <img class=\"col-sm-6\" src=\"logo.png\" alt=\"Card image cap\">\r\n"
115
                + "                    <div class=\"col-sm-6\">\r\n"
116
                + "                        <h5 class=\"card-title text-success\">" + book.getName() + "</h5>\r\n"
117
                + "                        <p class=\"card-text\">\r\n"
118
                + "                        Author: <span class=\"text-primary\" style=\"font-weight:bold;\"> "
119
                + book.getAuthor()
120
                + "</span><br>\r\n"
121
                + "                        </p>\r\n"
122
                + "                        \r\n"
123
                + "                    </div>\r\n"
124
                + "                </div>\r\n"
125
                + "                <div class=\"row card-body\">\r\n"
126
                + "                    <div class=\"col-sm-6\">\r\n"
127
                + "                        <p class=\"card-text\">\r\n"
128
                + "                        <span>Id: " + bCode + "</span>\r\n"
129
                + (bQty < 20 ? "<br><span class=\"text-danger\">Only " + bQty + " items left</span>\r\n"
130
                        : "<br><span class=\"text-success\">Trending</span>\r\n")
131
                + "                        </p>\r\n"
132
                + "                    </div>\r\n"
133
                + "                    <div class=\"col-sm-6\">\r\n"
134
                + "                        <p class=\"card-text\">\r\n"
135
                + "                        Price: <span style=\"font-weight:bold; color:green\"> &#8377; "
136
                + book.getPrice()
137
                + " </span>\r\n"
138
                + "                        </p>\r\n"
139
                + button
140
                + "                    </div>\r\n"
141
                + "                </div>\r\n"
142
                + "            </div>";
143
    }
144
}
145

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

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

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

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