Implementing Shopping Carts

shopping cart diagram

Part 1 - Create the java classes to perform the function of the cart and an item in the cart

ShoppingCart.java

package registrarbeans;


import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.jsp.JspWriter;
import java.sql.*;

/**
 *
 * @author Mark Pendergast
 */
public class ShoppingCart {
  
    ArrayList<Item> itemlist = new ArrayList<Item>();  // list of Items in the cart
    java.text.DecimalFormat currency = new java.text.DecimalFormat("$ #,###,##0.00");
  
    public ShoppingCart()
    {
      
    }
     public void empty()
     {
       itemlist.clear();
     }
    //
     // add an item to the cart
     // if its there already, just update the upc
     // 
    public void add(Item anitem)
    {
  
     for(int i = 0; i < itemlist.size(); i++)
     {
     Item item = itemlist.get(i);
      if(anitem.id == item.id) // already in the cart?
      {
       item.quantity += anitem.quantity; // yes, just update the quantity
       return;
      }
     }
     itemlist.add(anitem); // no, add it as a new item
    }
    //
    // remove an item with a given id from the shopping cart
    //
    public void remove(int id)
    {
  
     for(int i = 0; i < itemlist.size(); i++)
     {
      Item item = itemlist.get(i);
      if(id == item.id) // item in the cart?
      {
       itemlist.remove(i); // remove it
       break;
      }
     }
    
    }
   //
   // Display the current contents of the cart as an html table
   //
   public void display(JspWriter out) throws IOException
     {
      //
      // start the table and output the header row
      //
      out.println("<h3>Cart contents</h3>");
      out.println("<table border=1>");
      out.println("<tr><th>ID</th><th>Name</th><th>Price</th><th>Quantity</th><th>Total</th></tr>");
  
      double total = 0;
      //
      // output one item at a time from the cart, one item to a row table
      //
      for(int i = 0; i < itemlist.size(); i++)
      {
       Item item = (Item)itemlist.get(i);
       out.println("<tr><td>"+item.id+"</td>"+
                  "<td>"+item.name+"</td>"+
                  "<td align=right>"+ currency.format(item.price)+"</td>"+
                  "<td align=right>"+ item.quantity+"</td>"+
                  "<td align=right>"+ currency.format(item.price*item.quantity)+"</td>"+
                  "<td align=center><A href='removeItemFromCart.jsp?id="+item.id+"'>remove</A></TD></tr>");
       total += item.price*item.quantity;
      }
      //
      // add summary information (total, tax, grand total)
      //
       out.println("<tr><td colspan = 4>Total purchase</td>");
       out.println("<td align=right>"+currency.format(total)+"</td></tr>");
       out.println("<tr><td colspan = 4>Sales tax @6%</td>"+
                  "<td align=right>"+ currency.format(total*.06)+"</td></tr>");
       out.println("<tr><td colspan = 4>Amount due</td>"+
                  "<td align=right>"+ currency.format(total*1.06)+"</td></tr>");
       out.println("</table>");
       out.println("<a href='checkOut.jsp'><input type='Button' value='Register'/></A><br/>");

     }
    
   public int checkOut(String url, String studentid)
    {
        int result = 0; // tally the classes added
        try{
        // open a connection
          Connection con = null;
          Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");  // load the driver
          con = DriverManager.getConnection(url);
//       
// add entry to enroll table for each item
//
        PreparedStatement prep = con.prepareStatement("Insert into enroll (StudentID, CRN) values (?,?)");
     
        for(int i = 0; i < itemlist.size(); i++)
        {
           Item item = itemlist.get(i);
           prep.setString(1, studentid);
           prep.setInt(2, item.id);
           result += prep.executeUpdate();
        }
        itemlist.clear(); //empty the cart
        prep.close();
        con.close();
        }
        catch(Exception ex)
        {
          // unable to close the prepared statement 
        }
        return result;
    }
  
   
}



Item.java

package registrarbeans;

/**
 *
 * @author Mark Pendergast
 */

public class Item {

    int id = 0;
    String name = "";
    int quantity = 0;
    double price = 0;
  
    public Item()
    {
      
    }
  //
  // mutator methods
  //
    public void setId(int n)
    {
      id = n;
    }
     public void setName(String s)
    {
     name = s;
    }
     public void setQuantity(int n)
    {
      quantity = n;
    }
    
    public void setPrice(double n)
    {
      price = n;
    }
   //
   // Accessor methods
   //
    public int getId()
    {
      return id;
    }
    public String getName()
    {
      return name;
    }
   
   public int getQuantity()
   {
    return quantity;
   }
  
   public double getPrice()
   {
     return price;
   }
  
  
   @Override
   public String toString()
   {
     return id+" "+name+" "+quantity +" @ "+price;
   }
}


Part 2 - Create a Search form and corresponding JSP that finds the objects and provides "add to cart" links

FindCourse.html

-->
<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <div>
           
           <form name="findCourse"  method="post" action="findCourseWithAddToCart.jsp" >
                <Label for="course">Course</Label><input type ="text" id="course" name="course" size="12" /> <br/>
                <Label for="title">Title</Label><input type ="text" id="title" name="title" size="30" /> <br/>
                <Label for="instructor">Instructor</Label><input type ="text" id="instructor" name="instructor" size="30" /> <br/>
                <Label for="seatsleft">Seats left greater than</Label><input type ="text" id="seatsleft" name="seatsleft" size="6" /> <br/>
                <input type="submit" value="find courses" /> <input type="reset" value="clear" />                  
             </form>          
           
         </div>
      
    </body>
</html>





findCourseWithAddToCart.jsp


%--
    Document   : findCourse
    Created on : Oct 18, 2012, 2:37:49 PM
    Author     : mpenderg
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Courses</title>
    </head>
    <body>
        <h1>Courses that match</h1>
        <%
          String course = "";
          String title = "";
          String instructor = "";
          String seatsleftStr = "0";
          if(request.getParameter("course") != null)
              course = request.getParameter("course");
           if(request.getParameter("title") != null)
             title = request.getParameter("title");
           if(request.getParameter("instructor") != null)
              instructor = request.getParameter("instructor");
           if(request.getParameter("seatsleft") != null)
             seatsleftStr= request.getParameter("seatsleft");
          int seatsleft = 0;
       try{
           seatsleft = Integer.parseInt(seatsleftStr);
         }
       catch(Exception ex1)
      {
         out.println("Invalid value for seats left, using 0<br/>");
       }
         
    //   
   // database work
   //              
        try{
         // open a connection
          Connection con = null;
          Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");  // load the driver
          con = DriverManager.getConnection("jdbc:sqlserver://rubble.student.ad.fgcu.edu:1433;databaseName=sp12ism3232x;user=s12ISM3232;password=s12ISM3232;");
      // create the sql command
          PreparedStatement prep = con.prepareStatement("Select * from courseschedule where course like ? and title like ? and instructor like ? and seatsleft >= ?"); 
          prep.setString(1,course+"%");
          prep.setString(2,"%"+title+"%");
          prep.setString(3,instructor+"%");
          prep.setInt(4,seatsleft);
         
          ResultSet rs = prep.executeQuery();
   %>
    <table border ="1">
        <tr>
         <td>CRN </td>  
         <td>Course</td> 
         <td>Title </td> 
         <td>Credits </td> 
         <td>Instructor </td>
         <td>Max seats</td> 
         <td>Seats left</td> 
         <td>College </td             
        </tr>
     <%
          // process results one row at a timne    
          while(rs.next())
          {
          out.println("<tr>");
          out.println("<td>"+rs.getString(1)+"</td>");
          out.println("<td>"+rs.getString(2)+"</td>");
          out.println("<td>"+rs.getString(3)+"</td>");
          out.println("<td>"+rs.getString(4)+"</td>");
          out.println("<td>"+rs.getString(5)+"</td>");
          out.println("<td>"+rs.getString(6)+"</td>");
          out.println("<td>"+rs.getString(7)+"</td>");
          out.println("<td>"+rs.getString(8)+"</td>");
          out.println("<td><a href='deleteCourse.jsp?CRN="+rs.getString(1)+"'><input type='button' value='delete'/></A></td>");
          String name =rs.getString(2)+" "+rs.getString(3);
          name = java.net.URLEncoder.encode(name, "UTF-8");  // fix name into a url ok       
          out.println("<td><a href='addItemToCart.jsp?id="+rs.getString(1)+"&name="+name+"&quantity=1&price=9.95"+
                       "'><input type='button' value='add'/></A></td>");

         
           out.println("</tr>");
          }
        
%>
    </table>
<%
         prep.close();
         con.close();                 
        }
        catch(Exception ex)
        {
          out.println("Sorry, the system is unavailable<br/>");
          out.println(ex.toString()+"<br/>");
        }
       
        %>
    </body>
</html>




Part 3 - Create an add to cart JSP that responds to the link generated in part 2

addItemToCart.jsp

<%--
    Document   : addItemToCart
    Created on : Oct 24, 2012, 1:46:32 PM
    Author     : Mark Pendergast
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="registrarbeans.*"%>
<%@page errorPage = "errorPage.jsp" %>
<jsp:useBean id="item" class="registrarbeans.Item" scope = "request" />
<jsp:useBean id="cart" class="registrarbeans.ShoppingCart" scope ="session" />  
<jsp:setProperty name="item" property="*" />
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Shopping Cart</title>
    </head>
    <body>
      
   <%
    //
    // set the session's inactive interval
    //
     session.setMaxInactiveInterval(1800); // 30 minutes  
            
    //
    // now add the item to the cart
    //
    synchronized(session)  // lock the session
    { 
       cart.add(item); // cart uses ArrayList which is not thread safe so we locked
       cart.display(out); // tell the cart to send its contents to the browser
     }
    %> 
    </body>
</html>



Part 4 - Create JSP to handle removing an item from the cart

removeItemFromCart.jsp


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="cart" class="registrarbeans.ShoppingCart" scope ="session" />  
<%@page errorPage = "errorPage.jsp" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Remove</title>
    </head>
    <body>
     <%
   
             
          session.setMaxInactiveInterval(1800); // make session expire after 30 minutes
          //
          // Remove the item
          String idstr = request.getParameter("id");
          try
          {
           int id = Integer.parseInt(idstr);
            synchronized(session)  // lock the session
            {
             cart.remove(id);   
            }               
          }
          catch(Exception ex)
          {
            out.println("Error: "+ ex.toString()+ "<br/>");
          }
          cart.display(out);
          %>   
    </body>
</html>




Part 5 - Check out

checkOut.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="cart" class="registrarbeans.ShoppingCart" scope ="session" />  
<jsp:useBean id="student" class="registrarbeans.Student" scope="session" />
<%@page errorPage = "errorPage.jsp" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Checkout</title>
    </head>
    <body>
        <%
         session.setMaxInactiveInterval(1800); // make session expire after 30 minutes
        
          if(student.isLoggedIn())
          {
           synchronized(session)
            {
             cart.checkOut("jdbc:sqlserver://rubble.student.ad.fgcu.edu:1433;databaseName=sp12ism3232x;user=s12ISM3232;password=s12ISM3232;", student.getId() );
            }       
         }
         else
           response.sendRedirect("login.html"); 
            
        %>
    </body>
</html>


Part 6 - Displaying the receipt (course schedule)


printSchedule.jsp



<%@page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="student" class="registrarbeans.Student" scope="session" />
<%@page errorPage = "errorPage.jsp" %>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Course schedule</title>
    </head>
    <body>
        <h2>Courses</h2>
        <%

          if(!student.isLoggedIn())      
             response.sendRedirect("login.html");
          else
          {
        
           try{
            // load the driver and create the connection
            Connection con = null;
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");  // load the driver
            con = DriverManager.getConnection("jdbc:sqlserver://rubble.student.ad.fgcu.edu:1433;databaseName=sp12ism3232x;user=s12ISM3232;password=s12ISM3232;");
           
            PreparedStatement prep = con.prepareStatement("select courseSchedule.crn, courseSchedule.title, courseSchedule.instructor from courseschedule, enroll where enroll.studentid =  ? and  courseschedule.crn = enroll.crn");          
            prep.setString(1,student.getId());
            ResultSet rs = prep.executeQuery();
            out.println("<table>");
            out.println("<tr><th>CRN</th><th>Title</th><th>Instructor</th></tr>");
            while(rs.next())
            {
              out.println("<tr>");
              out.println("<td>"+rs.getString(1)+"</td>");
              out.println("<td>"+rs.getString(2)+"</td>");
              out.println("<td>"+rs.getString(3)+"</td>");
              out.println("</tr>");
            }
            out.println("</table>");
            prep.close();
          
            con.close();
           
            }
            catch(Exception ex)
            {
             out.println("Sorry, system is unavailable"); 
             out.println(ex.toString());          
                   
            }
        }
    %>  
 
    </body>
</html>