Session Tracking
Session Tracking
Disadvantages
E.g., http://host/path/file.html;jsessionid=1234
Advantage
Works even if cookies are disabled or unsupported
Disadvantages
Has a lot of tedious work to do processing to do
Searchstring = URLEncoder.encode(serchstring)
When redirecting, you need to use the above line to encode url to avoid
Advantage
Works even if cookies are disabled or unsupported
Disadvantages
Lots of tedious processing
For example:
Shopping Carts
Personalization Services
Maintaining state about the user’s preferences.
Overview of Session API Functionality
Using the Session API
Steps to using the Java Session API
1) Get the Session object from the HTTPRequest object.
2) Extract Data from the user’s Session Object
3) Extract information about the session object”
- e.g. when was the session created, session ID?
4) Add data to the user’s Session Object.
Session Tracking Basics
Access the session object
Call request.getSession to get HttpSession object
This is a hashtable associated with the user
Example:
HttpSession session = request.getSession();
If no session exists
a new one is created and returned.
For example:
HttpSession session = request.getSession(false);
Hash Map that enables you to store any type of Java object.
You can therefore store any number of keys and their
associated values.
use the
getAttributeNames() method.
key
Value
To remove a value, you can use the following:
removeAttribute (String name) method.
Terminating Sessions
public void invalidate()
If the user does not return to a servlet for XX minutes*,
the session is automatically invalidated and deleted.
The Servlet API provides methods to allow you to append the session ID to URLs
if the browser does not support cookies.
http://host/path/file.html;jsessionid=1234
If server is using URL rewriting, this appends the session info to the URL
Example.:
String url = "order-page.html";
url = response.encodeURL(url);
Since this is hard to ensure, lots of sites (e.g. Yahoo require cookies.)
Example Session Code
Example #1 Overview (9.1 in book)
Our example tracks the number of visits for each unique visitor.
If this is a first time visit,
the servlet creates an accessCount of Integer Integer
Type and assigns it to the Session.
If the user has visited before,
the servlet extracts the accessCount
and increments it,
and also
assigns it to the Session.
Servlet also displays
basic information regarding the session including
creation time and time of last access.
package coreservlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
The Session API hides all the ugly details from you, so you can focus
on your specific application.