Sessions

   session.setAttribute("name","Fred Flintstone");  //   sets a string object to the attribute called "name"
   String name = (String)session.getAttribute("name");
     session.setMaxInactiveInterval(600);   // timeout and destroy the session and its attributes after 10 minutes
Java classes and sessions
          <%@ page import="onlinecompany.*"%>
onlinecompany.ShoppingCart cart = new  onlinecompany.ShoppingCart();
session.setAttribute("Cart",cart);   //  add in the jsp 1
...
onlinecompany.ShoppingCart cart = (onlinecompany.ShoppingCart)session.getAttribute("Cart");     // retrieve in jsp 2
if(cart == null)  // new sesssion, just create a cart
{
  cart = new ShoppingCart();
  session.setAttribute("Cart", cart);
 }

HttpSession session = request.getSession();
 synchonized(session)  // lock the session object
{
  session.setAttribute("Cart",cart);   //  add in the jsp 1
} // release the lock

Click here to download the Session Shopping Cart Demo


Simple shopping cart example:


OrderForm.html


<html>
    <head>
        <title>Order Form</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
          
        <h2>Order Form</h2>
        <form name="orderform" method="post" action="orderItem.jsp" target="cartwindow">
            <table >
              <tr><td>UPC</td><td><input type="text" name="upc" size="10"></td></tr> 
              <tr><td>Name</td><td><input type="text" name="name" size="30"></td></tr>
              <tr><td>Quantity</td><td><input type="text" name="quantity" size="8"></td></tr>
              <tr><td>Price</td><td><input type="text" name="price" size="10"></td></tr>
              <tr><td colspan ="2" align="center">
               <input type="submit" value="Add" name="action">
               <input type="submit" value="Empty" name="action">
               <input type="reset" value="Clear">
               </td></tr>
            </table>
        </form>
        <p>
        <iframe width="600" height="300" name="cartwindow"></iframe>
       
    </body>
</html>




orderItem.jsp

<%--
    Document   : orderItem
    Created on : Oct 28, 2011, 2:36:26 PM
    Author     : Mark Pendergast
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="onlinecompany.*"%>
       
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
       
   <%
    //
    // set the session's inactive interval
    //
       session.setMaxInactiveInterval(1800); // 30 minutes
      
   //
   // get the action
   //
    String action = request.getParameter("action");
    if(action.equals("Add"))   // process add item
    {     
     //
    // first get the data from the html form
    //    
    try{              
      String upc = request.getParameter("upc");
      String name = request.getParameter("name");
      int quantity = Integer.parseInt(request.getParameter("quantity"));
      double price = Double.parseDouble(request.getParameter("price"));
   
    //
    // create an item to add to the cart
    //
      Item item = new Item(upc, name, quantity, price);
    //
    // now access the cart and add the item
    //
       synchronized(session)  // lock session protect this from multiple threads
      {
       ShoppingCart cart = (ShoppingCart)session.getAttribute("Cart");
       if(cart == null)  // new sesssion, just create a cart
       {
        cart = new ShoppingCart();
        session.setAttribute("Cart", cart);
       }
       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
      } // end synchronization lock
      }
      catch(Exception ex)
      {
       out.println(ex.toString()); // show the exception for now
      }
     }
    else
     if(action.equals("Empty"))
     {
       synchronized(session)  // lock session protect this from multiple threads
       {
        ShoppingCart cart = (ShoppingCart)session.getAttribute("Cart");
        if(cart == null)  // new sesssion, just create a cart
        {
         cart = new ShoppingCart();
         session.setAttribute("Cart", cart);
        }
        cart.empty(); // cart uses ArrayList which is not thread safe so we locked
        cart.display(out); // tell the cart to send its contents to the browser
       } // end synchronization lock 
     }
    %>
   
    </body>
</html>


ShoppingCart.java

package onlinecompany;

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

/**
 *
 * @author Mark Pendergast
 */
public class ShoppingCart {
   
    ArrayList<Item> itemlist = new ArrayList<Item>();  // list of Items in the cart
   
    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.upc.equals(item.upc)) // already in the cart?
      {
       item.quantity += anitem.quantity; // yes, just update the quantity
       return;
      }
     }
     itemlist.add(anitem); // no, add it as a new item
    }
    
   //
   // Display the current contents of the cart as an html table
   //
   public void display(JspWriter out)
     {
     try{
      java.text.DecimalFormat currency = new java.text.DecimalFormat("$ #,###,##0.00");
      //
      // start the table and output the header row
      //
      out.println("<h3>Cart contents</h3>");
      out.println("<table border=1>");
      out.println("<tr><th>UPC</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.upc+"</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></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>");

     }
     catch(IOException ex)
     {
      // exception was thrown by the out object, so we can't really report it to the client
      System.err.println(ex.toString());  // just send the exception to the error log
     }
   }
    
}



Item.java


package onlinecompany;

/**
 *
 * @author Mark Pendergast
 */
public class Item {

    String upc = "";
    String name = "";
    int quantity = 0;
    double price = 0;
   
    public Item()
    {
       
    }
   
    public Item(String upc, String name, int quantity, double price)
    {
     this.upc = upc;
     this.name = name;
     this.quantity= quantity;
     this.price = price;
    }
   
}