Servlet Shopping Cart Example


In this article, we are going to build a basic shopping cart using session tracking in servlet. We are going to sell pizza online. For that, we need an interface to show a list of available pizzas.

We are going to use basic HTML table layout to create our front end. Later we will use a servlet class and database to build up available items page.

You need to create a form for each item. We will be using a hidden item to send the data to our servlet. With the help of our hidden fields, we are sending the price and name of the item selected by the user.

<form action="addtocart">
<th>Pizza Name</th> <th>Price</th> <th>Add to Cart</th>
<tr><td>Muffuleta</td><td>$20</td>
<td><input type="hidden" name="name" value="Muffuleta">
<input type="hidden" name="price" value="20">
<input type="submit" value="Add to cart"></td></tr>
</form>

Repeat the above step for all items in the catalog. We have specified the name of the servlet that is going to handle the request in the action field of our form.

Screenshot

index.html

 

<!DOCTYPE html>
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
    </head>
    <body>
             <table border="1px">
        <form action="addtocart">
   
            <th>Pizza Name</th> <th>Price</th>  <th>Add to Cart</th>
            <tr><td>Muffuleta</td><td>$20</td><td><input type="hidden" name="name" value="Muffuleta">
            <input type="hidden" name="price" value="20"><input type="submit" value="Add to cart"></td>
        </tr>
        </form>
        <form action="addtocart">
            <tr><td>Veggie Delight</td><td>$40</td><td>
            <input type="hidden" name="name" value="Veggie Delight">
            <input type="hidden" name="price" value="40"><input type="submit" value="Add to cart"></td>
        </tr>  
        </form>
         <form action="addtocart">
            <tr><td>Margherita</td><td>$10</td><td>
            <input type="hidden" name="name" value="margherita">
            <input type="hidden" name="price" value="10"><input type="submit" value="Add to cart"></td>
            </tr>
           
        </form>
</table> 
    </body>
</html>

 

 

We are now going to create a session object for our shopping cart items. First we will create a class whose object will hold the shopping cart items by following this steps.

  1. Create a new Cart Java class.
    public class Cart {
    }
  2. Create a HashMap, which will hold details about items in the Cart.
      HashMap<String, Integer> cartItems;
  3. The Constructor of Cart class.
    public Cart(){
         cartItems = new HashMap<>();
     }
  4. Function to retrieve Cart items.
     public HashMap getCartItems(){
            return cartItems;
        }
  5. Add a new Item to the shopping cart.
     public void addToCart(String itemId, int price){
            cartItems.put(itemId, price);
        }
        
    

Complete Code

 

import java.util.HashMap;
/**
 *
 * @author rajat
 */
public class Cart {
    HashMap<String, Integer> cartItems;
    public Cart(){
     cartItems = new HashMap<>();
     
    }
    public HashMap getCartItems(){
        return cartItems;
    }
    public void addToCart(String itemId, int price){
        cartItems.put(itemId, price);
    }
    
}

Now create a session object that will hold our cart. We will check if the Cart returned by session exists or not. If it does not exist then, we will add new cart attribute to the session object. Then we will add the item to our cart. Follow the following steps to implement shopping cart through session tracking.

 

 

  • Create a reference of Cart, which will hold the pizza order items.
    Cart shoppingCart;
  • Retrieve the Cart attribute from the session object.
      HttpSession session = request.getSession();
      shoppingCart = (Cart) session.getAttribute("cart");
    
  • If shopping cart doesn't exist in the session, then set a new attribute.
     if(shoppingCart == null){
              shoppingCart = new Cart();
              session.setAttribute("cart", shoppingCart);
            }

 

Now we will add pizza items selected by the user to our shopping cart. We are also going to display the items from the cart by sending HTML as a response from our servlet.

Add Item To Shopping Cart

  • Fetch Selected data.
    String name = request.getParameter("name");
    Integer price = Integer.parseInt(request.getParameter("price"));
    
  • Put data in a hashmap.
    shoppingCart.addToCart(name, price);
  • Update cart.
     session.setAttribute("cart", shoppingCart);
    

Display Items From Shopping Cart

  1. Get value from the shopping cart and assign it to a HashMap.
    HashMap<String, Integer> items = shoppingCart.getCartItems();
  2. Create a new table to display our pizza cart.
    out.println("<table border='1px'>");
  3. Each item in the HashMap will contain one row from our HTML table.
     for(String key: items.keySet()){
                    out.println("<tr><td>"+key+" - </td><td>"+"$"+items.get(key)+"</td></tr>");
                }
    

Screenshot

 

 

Shopping Card Servlet Example

public class Addtocart extends HttpServlet {
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession();
        cart shoppingCart;
        shoppingCart = (cart) session.getAttribute("cart");
        if(shoppingCart == null){
          shoppingCart = new cart();
          session.setAttribute("cart", shoppingCart);
        }
        String name = request.getParameter("name");
        Integer price = Integer.parseInt(request.getParameter("price"));
        shoppingCart.addToCart(name, price);
        session.setAttribute("cart", shoppingCart);
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>result</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Pizza successfully added to cart </h1>");
            out.println("<form action='index.html'>Add more pizza item<input type='submit' value='go'></form>");
            out.println("<hr>");
            out.println("<h2>Cart</h2>");
            HashMap<String, Integer> items = shoppingCart.getCartItems();
            out.println("<table border='1px'>");
            
            for(String key: items.keySet()){
                out.println("<tr><td>"+key+" - </td><td>"+"$"+items.get(key)+"</td></tr>");
            }
            out.println("<table>");
            out.println("</body>");
            out.println("</html>");
            
        }
    }

We have fetched and displayed the pizza items from our shopping cart. Now we are adding an option to delete an item from the cart.

In Addtocart servlet add the following code inside processRequest() function after HTML table tag.

 for(String key: items.keySet()){
                out.println("<form action='deleteItem'><input type='hidden' name='name' value='"+key+"'>
                             <tr><td>"+key+" - </td><td>"+"$"+items.get(key)+"</td><td>
                             <input type='submit' value='delete'></td></tr></form>");
            }

We have included the name of the article that should be removed in our hidden input field. When a user clicks the delete button, he will be redirected to the DeleteItem servlet.

Implementation of DeleteItem Servlet

To delete an item from the servlet, we need to modify our cart class. Add a deleteFromCart() function.

public void deleteFromCart(String itemId){
        cartItems.remove(itemId);
    }

Now follow the steps given below to remove an item from the session object.

  1. Fetch shopping cart from the session object.
    HttpSession session = request.getSession();
    Cart shoppingCart;
    shoppingCart = (Cart) session.getAttribute("cart");
  2. Delete an item from the cart.
      shoppingCart.deleteFromCart(name);
    
  3. Update and fetch new cart.
    //update
    session.setAttribute("cart", shoppingCart);
    // now fetch
    shoppingCart = (Cart) session.getAttribute("cart");
    

Complete code to delete items from the shopping cart

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String name = request.getParameter("name");
          HttpSession session = request.getSession();
        cart shoppingCart;
        shoppingCart = (cart) session.getAttribute("cart");
        shoppingCart.deleteFromCart(name);
        session.setAttribute("cart", shoppingCart);
         shoppingCart = (cart) session.getAttribute("cart");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet deleteItem</title>");            
            out.println("</head>");
            out.println("<body>");
            HashMap<String, Integer> items = shoppingCart.getCartItems();
            out.println("<table border='1px'>");
            
            for(String key: items.keySet()){
                out.println("<form action='deleteItem'><input type='hidden' name='name' value='"+key+"'><tr><td>"+key+" - </td><td>"+"$"+items.get(key)+"</td><td><input type='submit' value='delete'></td></tr></form>");
            }
            out.println("<table>");
            out.println("</body>");
            out.println("</html>");
        }
    }