Session Management in Servlets - Shopping Cart Application Readme

Session Management in Servlets - Shopping Cart Application Readme

Date: 18/Mar/2004

Table of Contents

Introduction
Application Overview
Application Design
Sample Application Files
Setting Up the Sample Application
Additional References

Introduction 

Prerequisite 

To understand this sample you need to have expertise in working with Servlets.

Technical Overview 

This sample application demonstrates how a servlet application can store and manage information in the HttpSession object.  javax.servlet.http.HttpSession is an interface that provides a way to identify a user across more than one page request or visit to a web site. It also allows the user to store and  maintain state data and application data. In particular, the HttpSession interface object supports methods to add/remove objects from the session. It stores and returns standard session properties such as a session identifier and application data. These values are stored as a name-value pair. The method for storing objects in a session is setAttribute(String s, Object o), and the method for retrieving stored objects in a session is the getAttribute(String s) method.

 A session usually corresponds to one user, who may visit a site many times. The server can maintain a session in many ways such as using cookies or rewriting URLs. The session persists for a specified time period, called as timeout period, across more than one connection or page request from the user. If a user does not come back for a certain period of time, the user's session expires and the corresponding HttpSession object is removed from memory. The default timeout period for sessions is defined by the servlet container and can be obtained via the getMaxInactiveInterval method. This timeout can be changed by using the setMaxInactiveInterval. The timeout periods used by these methods is defined in seconds. If the timeout period for a session is set to -1, the session will never expire. When a session expires or invalidates, the HttpSession object and its values are removed from the system. 

For more information about the implementation details go to code support section.

Application Overview 

The sample application allows the user to browse though the available products and then create a shopping cart, update the cart with the quantity, remove the items from the cart and finally checkout the cart.

Application Design 

This section will detail application design notes that will help you appreciate the design decisions that went into developing this sample application, the architecture diagram that lets you visualize how different components fit together in the overall scheme of the application, and code snippets that help you relate the implementation of concepts in code.

Design Notes 

This application is designed to demonstrate how HttpSession object can be used to store and maintain application data in the session. In this sample all the application data like; user name, product ids and, the shopping cart (product details) are stored in the HttpSession  object. When the user logs in to the application using the default 'guest/welcome' user name and password, the user name is stored in the session and the user is redirected to the product listing page.
User can then select any of the available products and add to the shopping cart. These items' details and product ids are stored in the session and displayed to the user. User can delete the item from the shopping cart or update the quantity of the item in the session. Finally when the cart is checked out  and all the product information is removed from the session. When the session expires after 60 seconds the user is directed to the login page. Also the session is invalidated when the user logs out from the application.

 Code Support

Each user session lasts for a particular time period called as session timeout interval. The default value is specified by the servlet container.
You can set this value by calling
setMaxInactiveInterval(int maxInterval).The integer value specifies the timeout period in seconds.
The below code from the addCart() method shows how the time out period is set to one minute for this application.


 public void addToCart(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException {

HttpSession session = request.getSession();

// Set the session time out as one minute
session.setMaxInactiveInterval(60);

.....................

}


Following is the code snippet of the addToCart() method:
The 
request.getSession() method returns the current session associated with this request, or if the request does not have a
session, it creates one.


 public void addToCart(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException {

HttpSession session = request.getSession();

String productId[] =(String[]) request.getParameterValues("ProductIds") ;

.................

// Get the ids of the products added to the cart
productIdsInCart = (ArrayList)session.getAttribute("productIdsInCart");

productDetails = new ProductDetails();
productDetails.setProductId(productId[i]);


String qty = (String) request.getParameter( ("qty"+productId[i]));
productDetails.setQuantity(Integer.parseInt( (qty==null)?"-1":qty));

String price = (String) request.getParameter(("unitPrice"+productId[i]));

productDetails.setUnitPrice( Float.parseFloat( ( price ==null)?"-1.0":price));

productIdsInCart.add(productId[i]);

session.setAttribute("productIdsInCart",productIdsInCart);

}

When the removeAttribute(java.lang.String attributeName) method is called on the session, that object is removed from the session.
The following code snippet shows how the productIds and productDetails of the shopping cart are removed from the session.

 public void checkoutCart( HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException {

HttpSession session = request.getSession();
ArrayList productIdsIncart = (ArrayList)session.getAttribute("productIdsInCart");

..............

// Remove the ids from the session
session.removeAttribute("productIdsInCart");

for (int i = 0; i < productIdsIncart.size(); i++) {
// Remove the shopping cart items from the session
session.removeAttribute((String)productIdsIncart.get(i));
}
}


The session can be invalidated by calling session.invalidate() method. This removes all the session informations associated with the current user session. The following code is from SessionServlet.java. It invalidates the session when the user logs out.

 String actionEvent =null; 
actionEvent=(String)request.getParameter("actionEvent");

if( actionEvent !=null && actionEvent.equals("logOut") ) {
session.invalidate();
}


You can find more details of the code in file EditCart.java under folder src/oracle/otnsamples/servlets.
Look into the Sample Application Files section for other details.

Sample Application Files 

This section will provide a tabular listing of the sample application files, along with their respective directory locations and a description of what they do in the overall scheme of the application:

Readme file and Stylesheets

Directory File Description

servlet/doc

Readme.html

This file

servlet/doc

otn.css
Stylesheet used in the Readme.html


Servlet and Java Server Page files for the Application

Directory File Description

servlet/src/oracle/otnsamples/servlets

SessionServlet.java

This Servlet displays the various screens of the application

servlet/src/oracle/otnsamples/servlets EditCart.java
The servlet used to manage the shopping cart in the HTTP Session
servlet/public_html/WEB-INF
web.xml
The web deployment descriptor
servlet build.xml The ant project build file


Java Source files for the Application

 Directory File Description

servlet/src/oracle/otnsamples/servletsample

ProductDetails.java

The Java helper class that used to store the order items information.


Setting up the Sample Application 

Refer the Install.html for step-by-step instructions on extracting files, installing and running the sample successfully.

Additional References 

We hope you find this README file helpful. Please enter your comments about this sample in the OTN Sample Code Discussion Forum.

Session Management in Servlets - Sample Application

Please rate this sample application :
Excellent
Good
Average
Below Average
Poor
E-mail this page
Printer View Printer View
Oracle Is The Information Company About Oracle | Oracle RSS Feeds | Careers | Contact Us | Site Maps | Legal Notices | Terms of Use | Privacy