Sessions
- HttpSession interface provides the JSP with the ability to store
and
share information between jsp files for an ongoing interaction with a
user.
- Every distinct user who starts and interaction with any JSP of an
application
is associated with a unique sesssion object.
- The session id is stored as a cookie on the user's machine. This
cookie
allows the server to associate a user with an active session.
- Sessions have lifetimes and will expire after a period of
inactivity.
- The lifetime can be set and accessed by methods of the session
object
- setMaxInactiveInterval(int) - sets the maximum time a session
can
be inactive before becoming invalid (in seconds)
- getMaxInactiveInterval() - retrieves this maximum inactiver
interval
(in seconds)
- Sessions can be used to store attribues (objects) that should
survive
for the lifetime of the session
- void setAttribute(String name, Object obj) - stores an objects
as
a session attribute
- Object getAttribute(String name) - retrieves the attribute.
- these objects are usually instances of java beans.
- If you are coding in a JSP, then the session object is already
available, in a Servlet, you need to get the session from the request
object
HttpSession session = request.getSession();
- if the session associated with the web user exists, it is
returned, if not, a new one is created.
- HttpSession is a "container" type class, it is used to
store objects (Java beans) across requests within the same session.
- you'll have to import javax.servlet.http.HttpSession to use it..
- to store an object in a HttpSession, use the setAttribute method,
e.g.
session.setAttribute("name","Fred Flintstone");
// sets a string object to the attribute called "name"
- to get the attribute back in subsequent requests, use
getAttribute method, this method returns null if the attribute is not
associated with the session, e.g.
String name =
(String)session.getAttribute("name");
- you should always set the inactive timeout interval (in seconds)
for your session, e.g.
session.setMaxInactiveInterval(600); //
timeout and destroy the session and its attributes after 10 minutes
- Other useful methods:
- session.getLastAccessedTime(); // returns the time the
client last sent a request assoicatied with the session (long)
- session.invalidate(); // has the effect of removing
all attributes objects from the session
- session.removeAttribute("name"); // removes the attribute
object with the specified name
- session.isNew(); // returns true if the session was
just created
Java classes and sessions
- Java objects can be created with the "new" operator just like you
did for desktop applications.
- In Netbeans, your web
project will have a "src" directory, within that is a "java"
directory. To create a java class, first create a package in the
Source Packages under your project, then create the class within the
package.
- You will need to import the package, or fully qualify the class
name of
the bean
<%@ page
import="onlinecompany.*"%>
- For example, if you had java class named "ShoppingCart" are in a
package called "onlinecompany", then you could create a new
ShoppingCart object using
onlinecompany.ShoppingCart cart =
new onlinecompany.ShoppingCart();
- To make an object live throughout the lifetime of the
session, you need to add it to the session during the request
that it was created, then access it other requests., eg.
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);
}
- Note, it is possible for a user to have multiple browser windows
open at the same time, effectively creating multiple threads on the
server that are accessing the session at the same time. This can
cause problems, so to prevent that, place all code that adds items to
the session in a synchronized block. e.g.
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;
}
}