WEB JAVA
package com.demo.servlets;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.demo.beans.CartItem;
import com.demo.beans.Product;
import com.demo.service.ProductService;
import com.demo.service.ProductServiceImpl;
/**
* Servlet implementation class AddToCart
*/
@WebServlet(name = "AddOrShowCart", urlPatterns = { "/addToCart" })
public class AddToCart extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String BUTTON_ADD = "add";
private static final String BUTTON_SHOW = "show";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String btn = request.getParameter("btn");
RequestDispatcher rd;
switch (btn) {
case BUTTON_ADD:
// Retrieve cart from session object if it exists
HttpSession sess = request.getSession();
List<CartItem> clist = (List<CartItem>) sess.getAttribute("cart");
// Create a new list if the cart does not exist
if (clist == null) {
clist = new ArrayList<>();
}
String[] parr = request.getParameterValues("prod");
ProductService pservice = new ProductServiceImpl();
if (parr != null) {
for (String id : parr) {
try {
int productId = Integer.parseInt(id);
Product p1 = pservice.getById(productId);
String qtyString = request.getParameter("p" + id);
int ordQty = (qtyString != null && !qtyString.trim().isEmpty()) ? Integer.parseInt(qtyString) : 0;
if (p1.getQty() >= ordQty && ordQty > 0) {
CartItem c = new CartItem(p1.getPid(), p1.getPname(), ordQty, p1.getPrice());
clist.add(c);
} else {
// Handle insufficient stock or invalid quantity
System.out.println("Insufficient stock for product ID: " + productId + ". Available: " + p1.getQty() + ", Requested: " + ordQty);
// Optionally, you could add a message to the request to inform the user
}
} catch (NumberFormatException e) {
System.out.println("Invalid product ID or quantity: " + id);
} catch (Exception e) {
System.out.println("Error retrieving product: " + e.getMessage());
}
}
} else {
System.out.println("No products selected.");
}
System.out.println(clist);
sess.setAttribute("cart", clist);
rd = request.getRequestDispatcher("categories");
rd.forward(request, response);
break;
ADD TO CART
case BUTTON_SHOW:
rd = request.getRequestDispatcher("showcart.jsp");
rd.forward(request, response);
break;
default:
System.out.println("Invalid button action.");
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid action.");
break;
}
}
}
SHOW PRODUCT.JSP
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1> Select Products</h1>
<table>
<form action="addToCart">
<tr> <th> </th>
<th>Product Name </th>
<th>Price </th>
<th> Quantity</th>
</tr>
<c:forEach var="p" items="${plist}">
<tr><td> <input type="checkbox" name="prod" id="${p.pid }" value="${p.pid}">
</td>
<td> ${p.pname} </td>
<td> ${p.price}</td>
<td><input type="text" name="p${p.pid}" id="${p.pid }" ></td> </tr>
</c:forEach>
<tr>
<td colspan="2"><button type="submit" name="btn" id="add" value="add">Add to Cart</button> </td>
<td colspan="2"> <button type="submit" name="btn" id="show" value="show">Show Cart</button></td>
</tr>
</form>
</table>
</body>
</html>
Comments
Post a Comment