Skip to content

Commit

Permalink
Merge pull request #110 from shashirajraja/feature/cart
Browse files Browse the repository at this point in the history
comments and formatting
  • Loading branch information
shashirajraja authored Mar 14, 2023
2 parents 7f69dce + 011fad3 commit d604f45
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 24 deletions.
25 changes: 23 additions & 2 deletions src/main/java/com/bittercode/util/StoreUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,22 @@

import com.bittercode.model.UserRole;

/*
* Store UTil File To Store Commonly used methods
*/
public class StoreUtil {

/**
* Check if the User is logged in with the requested role
*/
public static boolean isLoggedIn(UserRole role, HttpSession session) {

return session.getAttribute(role.toString()) != null;
}

/**
* Modify the active tab in the page menu bar
*/
public static void setActiveTab(PrintWriter pw, String activeTab) {

pw.println("<script>document.getElementById(activeTab).classList.remove(\"active\");activeTab=" + activeTab
Expand All @@ -22,23 +31,35 @@ public static void setActiveTab(PrintWriter pw, String activeTab) {

}

/**
* Add/Remove/Update Item in the cart using the session
*/
public static void updateCartItems(HttpServletRequest req) {
String selectedBookId = req.getParameter("selectedBookId");
HttpSession session = req.getSession();
if (selectedBookId != null) { // add item to the cart

// Items will contain comma separated bookIds that needs to be added in the cart
String items = (String) session.getAttribute("items");
if (req.getParameter("addToCart") != null) { // add to cart
if (items == null)
items = selectedBookId;
else if (!items.contains(selectedBookId))
items = items + "," + selectedBookId;
items = items + "," + selectedBookId; // if items already contains bookId, don't add it

// set the items in the session to be used later
session.setAttribute("items", items);

/*
* Quantity of each item in the cart will be stored in the session as:
* Prefixed with qty_ following its bookId
* For example 2 no. of book with id 'myBook' in the cart will be
* added to the session as qty_myBook=2
*/
int itemQty = 0;
if (session.getAttribute("qty_" + selectedBookId) != null)
itemQty = (int) session.getAttribute("qty_" + selectedBookId);
itemQty += 1;

session.setAttribute("qty_" + selectedBookId, itemQty);
} else { // remove from the cart
int itemQty = 0;
Expand Down
20 changes: 15 additions & 5 deletions src/main/java/servlets/CartServlet.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,25 +27,33 @@ public class CartServlet extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
PrintWriter pw = res.getWriter();
res.setContentType(BookStoreConstants.CONTENT_TYPE_TEXT_HTML);

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

HttpSession session = req.getSession();
String bookIds = "";
if (session.getAttribute("items") != null)
bookIds = (String) session.getAttribute("items");// comma seperated bookIds
bookIds = (String) session.getAttribute("items");// read comma separated bookIds from session

RequestDispatcher rd = req.getRequestDispatcher("Sample.html");
rd.include(req, res);

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

// Read the books from the database with the respective bookIds
List<Book> books = bookService.getBooksByCommaSeperatedBookIds(bookIds);
List<Cart> cartItems = new ArrayList<Cart>();

pw.println("<div id='topmid' style='background-color:grey'>Shopping Cart</div>");
pw.println("<table class=\"table table-hover\" style='background-color:white'>\r\n"
+ " <thead>\r\n"
Expand All @@ -72,6 +80,8 @@ public void service(HttpServletRequest req, HttpServletResponse res) throws IOEx
amountToPay += (qty * book.getPrice());
pw.println(getRowData(cart));
}

// set cartItems and amountToPay in the session
session.setAttribute("cartItems", cartItems);
session.setAttribute("amountToPay", amountToPay);

Expand Down Expand Up @@ -105,8 +115,8 @@ public String getRowData(Cart cart) {
+ " <td>" + book.getAuthor() + "</td>\r\n"
+ " <td><span>&#8377;</span> " + book.getPrice() + "</td>\r\n"
+ " <td><form method='post' action='cart'><button type='submit' name='removeFromCart' class=\"glyphicon glyphicon-minus btn btn-danger\"></button> "
+ "<input type='hidden' name='selectedBookId' value='"+book.getBarcode()+"'/>"
+ cart.getQuantity()
+ "<input type='hidden' name='selectedBookId' value='" + book.getBarcode() + "'/>"
+ cart.getQuantity()
+ " <button type='submit' name='addToCart' class=\"glyphicon glyphicon-plus btn btn-success\"></button></form></td>\r\n"
+ " <td><span>&#8377;</span> " + (book.getPrice() * cart.getQuantity()) + "</td>\r\n"
+ " </tr>\r\n";
Expand Down
65 changes: 48 additions & 17 deletions src/main/java/servlets/ViewBookServlet.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,15 @@
import com.bittercode.util.StoreUtil;

public class ViewBookServlet extends HttpServlet {

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

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

// Check if the customer is logged in, or else return to login page
if (!StoreUtil.isLoggedIn(UserRole.CUSTOMER, req.getSession())) {
RequestDispatcher rd = req.getRequestDispatcher("UserLogin.html");
rd.include(req, res);
Expand All @@ -31,62 +35,88 @@ public void service(HttpServletRequest req, HttpServletResponse res) throws IOEx
}
try {

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

// Default Page to load data into
RequestDispatcher rd = req.getRequestDispatcher("Sample.html");
rd.include(req, res);

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

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

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

HttpSession session = req.getSession();
for (Book book : books) {
pw.println(this.addBookToCard(session, book.getBarcode(), book.getName(), book.getAuthor(),
book.getPrice(),
book.getQuantity()));

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

}

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

} catch (Exception e) {
e.printStackTrace();
}
}

public String addBookToCard(HttpSession session, String bCode, String bName, String bAuthor, double bPrice,
int bQty) {
String button = "<p class=\"btn btn-danger\">Out Of Stock</p>\r\n";
public String addBookToCard(HttpSession session, Book book) {
String bCode = book.getBarcode();
int bQty = book.getQuantity();

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

// Button To Add/Remove item from the cart
String button = "";
if (bQty > 0) {
// If no items in the cart, show add to cart button
// If items is added to the cart, then show +, - button to add/remove more items
button = "<form action=\"viewbook\" method=\"post\">"
+ "<input type='hidden' name = 'selectedBookId' value = " + bCode + ">"
+ "<input type='hidden' name='qty_" + bCode + "' value='1'/>"
+ ""
+ (cartItemQty == 0 ? "<input type='submit' class=\"btn btn-primary\" name='addToCart' value='Add To Cart'/></form>"
:"<form method='post' action='cart'><button type='submit' name='removeFromCart' class=\"glyphicon glyphicon-minus btn btn-danger\"></button> "
+ "<input type='hidden' name='selectedBookId' value='"+bCode+"'/>"
+ cartItemQty
+ " <button type='submit' name='addToCart' class=\"glyphicon glyphicon-plus btn btn-success\"></button></form>" )
+ (cartItemQty == 0
? "<input type='submit' class=\"btn btn-primary\" name='addToCart' value='Add To Cart'/></form>"
: "<form method='post' action='cart'>"
+ "<button type='submit' name='removeFromCart' class=\"glyphicon glyphicon-minus btn btn-danger\"></button> "
+ "<input type='hidden' name='selectedBookId' value='" + bCode + "'/>"
+ cartItemQty
+ " <button type='submit' name='addToCart' class=\"glyphicon glyphicon-plus btn btn-success\"></button></form>")
+ "";
} else {
// If available Quantity is zero, show out of stock button
button = "<p class=\"btn btn-danger\">Out Of Stock</p>\r\n";
}

// Bootstrap card to show the book data
return "<div class=\"card\">\r\n"
+ " <div class=\"row card-body\">\r\n"
+ " <img class=\"col-sm-6\" src=\"logo.png\" alt=\"Card image cap\">\r\n"
+ " <div class=\"col-sm-6\">\r\n"
+ " <h5 class=\"card-title text-success\">" + bName + "</h5>\r\n"
+ " <h5 class=\"card-title text-success\">" + book.getName() + "</h5>\r\n"
+ " <p class=\"card-text\">\r\n"
+ " Author: <span class=\"text-primary\" style=\"font-weight:bold;\"> " + bAuthor
+ " Author: <span class=\"text-primary\" style=\"font-weight:bold;\"> "
+ book.getAuthor()
+ "</span><br>\r\n"
+ " </p>\r\n"
+ " \r\n"
Expand All @@ -102,7 +132,8 @@ public String addBookToCard(HttpSession session, String bCode, String bName, Str
+ " </div>\r\n"
+ " <div class=\"col-sm-6\">\r\n"
+ " <p class=\"card-text\">\r\n"
+ " Price: <span style=\"font-weight:bold; color:green\"> &#8377; " + bPrice
+ " Price: <span style=\"font-weight:bold; color:green\"> &#8377; "
+ book.getPrice()
+ " </span>\r\n"
+ " </p>\r\n"
+ button
Expand Down

0 comments on commit d604f45

Please sign in to comment.