0

I am buliding an online bookstore with JSP and servlet which allow the user to view books and add to cart then process to checkout, but when I add an item to my cart and then I click on view cart it says cart is empty.

this is my AddToCart.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ page import="java.util.*" %>
<%@ page session="true" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Item Added to Cart</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="flex items-center justify-center h-screen bg-gray-100">
<div class="bg-white shadow-md rounded-lg p-8 max-w-sm w-full">
    <h2 class="text-2xl font-bold text-gray-800 mb-4">Item Added to Cart</h2>
    <p class="text-gray-600 mb-4">
        You have successfully added <strong><%= request.getParameter("title") %></strong> to your cart.
    </p>
    <div class="flex justify-between mt-6">
        <a href="Cart.jsp" class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 transition duration-300">
            View Cart
        </a>
        <a href="home.jsp" class="bg-gray-300 text-gray-800 px-4 py-2 rounded hover:bg-gray-400 transition duration-300">
            Continue Shopping
        </a>
    </div>
</div>
</body>
</html>

here is the AddToCartServlet.java:

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 java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/addToCart")
public class AddToCartServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // Retrieve the item details from the request
        String title = request.getParameter("title"); // Get item title from request
        int id = Integer.parseInt(request.getParameter("id")); // Get item ID from request

        // Create a new item
        Item newItem = new Item(id, title);

        // Get the user's session
        HttpSession session = request.getSession();

        // Retrieve the cart from the session
        List<Item> cart = (List<Item>) session.getAttribute("cart");
        if (cart == null) {
            cart = new ArrayList<>(); // If cart doesn't exist, initialize it
        }


        // Add the new item to the cart
        cart.add(newItem);
        session.setAttribute("cart", cart); // Update the session with the new cart

        // Redirect to the confirmation page with the item title
        response.sendRedirect("cartConfirmation.jsp?title=" + URLEncoder.encode(title, "UTF-8"));
    }

    // Item class to represent an item in the cart
    private static class Item {
        private int id;
        private String title;

        public Item(int id, String title) {
            this.id = id;
            this.title = title;
        }

        public int getId() {
            return id;
        }

        public String getTitle() {
            return title;
        }
    }
}

and then my cart.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ page import="java.util.*" %>
<%@ page session="true" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Your Cart</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100">
<div class="container mx-auto p-4">
    <h1 class="text-3xl font-bold text-gray-800 mb-4">Your Cart</h1>

    <%
        List<Map<String, String>> cart = (List<Map<String, String>>) session.getAttribute("cart");
        if (cart == null || cart.isEmpty()) {
    %>
    <div class="bg-white shadow-md rounded-lg p-6">
        <p class="text-gray-600">Your cart is currently empty.</p>
        <a href="home.jsp" class="mt-4 inline-block bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 transition duration-300">
            Continue Shopping
        </a>
    </div>
    <%
    } else {
    %>
    <div class="bg-white shadow-md rounded-lg p-6">
        <table class="min-w-full border">
            <thead>
            <tr class="bg-gray-200 text-gray-600">
                <th class="py-3 px-4 text-left">Item</th>
                <th class="py-3 px-4 text-left">Author</th>
                <th class="py-3 px-4 text-left">Price</th>
                <th class="py-3 px-4 text-left">Actions</th>
            </tr>
            </thead>
            <tbody>
            <%
                double total = 0.0; // To calculate total price
                for (Map<String, String> item : cart) {
                    String title = item.get("title");
                    String author = item.get("author");
                    String price = item.get("price");
                    double itemPrice = Double.parseDouble(price);
                    total += itemPrice; // Add to total price
            %>
            <tr>
                <td class="py-3 px-4 border-b"><%= title %></td>
                <td class="py-3 px-4 border-b"><%= author %></td>
                <td class="py-3 px-4 border-b">$<%= price %></td>
                <td class="py-3 px-4 border-b">
                    <form action="removeFromCart.jsp" method="post" class="inline">
                        <input type="hidden" name="itemTitle" value="<%= title %>">
                        <button type="submit" class="text-red-600 hover:underline">Remove</button>
                    </form>
                </td>
            </tr>
            <%
                }
            %>
            </tbody>
        </table>
        <div class="mt-4">
            <p class="text-gray-800 font-bold">Total: $<%= String.format("%.2f", total) %></p>
        </div>
        <div class="mt-6">
            <a href="checkout.jsp" class="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600 transition duration-300">
                Proceed to Checkout
            </a>
        </div>
    </div>
    <%
        }
    %>
</div>
</body>
</html>

I want the cart to be able to display the item added, and then proceed to checkout, the proceeded item should be sent to the admin dashborad.

1
  • You need to learn basics of Java, this the point to start with. Commented Nov 29, 2024 at 19:47

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.