Session Tracking
A Session refers to the entire request that a
single client makes to a server. A session is specific to the user and for each
user a new session is created to track all the request from that user. Every
user has a separate session and separate session variable is associated with
that session.
HTTP is stateless protocol and it does not maintain
the client state. But there exist a mechanism called "Session
Tracking" which helps the servers to maintain the state to track the
series of requests from the same user across some period of time.
A session ID is an unique identification string
usually a long, random and alpha-numeric string, that is transmitted between
the client and the server. Session IDs are usually stored in the cookies, URLs
(in case url rewriting) and hidden fields of Web pages.
The Need for Session Tracking
HTTP is a
―stateless‖ protocol: each time a client retrieves a Web page, the client opens
a separate connection to the Web server and the server does not automatically
maintain contextual information about the client. Even with servers that
support persistent (keep-alive) HTTP connections and keep sockets open for
multiple client requests that occur in rapid succession, there is no built-in
support for maintaining contextual information. This lack of context causes a
number of difficulties.
For
example, when clients at an online store add an item to their shopping carts,
how does the server know what‘s already in the carts? Similarly, when clients
decide to proceed to checkout, how can the server determine which previously
created shopping carts are theirs?
There are
three typical solutions to this problem:
• cookies,
• URL
rewriting
• Hidden
form fields.
• User
Authorization
Session Tracking Basics
1. Accessing the session object associated
with the current request.
Call
request.getSession to get an HttpSession object, which is a simple hash table
for
storing
user-specific data.
2. Looking up information associated with a
session.
Call getAttribute on the HttpSession object,
cast the return value to the appropriate type, and check whether the result is
null.
3. Storing information in a session.
Use
setAttribute with a key and a value.
4. Discarding session data.
Call removeAttribute to discard a specific
value. Call invalidate to discard an entire session. Call logout to log the
client out of the Web server and invalidate all sessions associated with that
user.
public
interface HttpSession
Provides
a way to identify a user across more than one page request or visit to a Web
site and to store information about that user.
The
servlet container uses this interface to create a session between an HTTP
client and an HTTP server. The session persists for a specified time period,
across more than one connection or page request from the user. 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.
This
interface allows servlets to
• View and
manipulate information about a session, such as the session identifier,
creation time, and last accessed time
• Bind
objects to sessions, allowing user information to persist across multiple user
connections
Obtaining a Session
The
getSession method of the HttpServletRequest object returns a user's session.
When you call the method with its create argument as true, the implementation
creates a session if necessary. The Duke's Bookstore example uses session
tracking to keep track of the books in the user's shopping cart. Here is an
example of theCatalogServlet obtaining a session for a user:
public
class CatalogServlet extends HttpServlet {
public
void doGet (HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
{
// Get
the user's session and shopping cart
HttpSession session =
request.getSession(true);
...
out =
response.getWriter();
...
}
}
Storing and Getting Data from a Session
The
HttpSession interface provides methods that store and return
• Standard
session properties, such as a session identifier
• Application
data, which is stored as a name-value pair, where the name is a String and the
value is an object in the Java programming language. (This is like
java.util.Dictionary.) Because multiple servlets have access to a user's
session, it should adopt a naming convention for
organizing
the names associated with application data. The Duke's Bookstore example uses
session tracking to keep track of the books in the user's shopping cart.
Here is
an example of theCatalogServlet getting a user's session identifier, and
getting and setting the application data associated with the user's session:
public
class CatalogServlet extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
// Get the
user's session and shopping cart HttpSession session = request.getSession(true);
ShoppingCart
cart = (ShoppingCart)session.getValue(session.getId());
// If the user has no cart, create a new one if
(cart == null) {
cart =
new ShoppingCart(); session.putValue(session.getId(), cart);
}
...
}
}
Because
an object can be associated with a session, the Duke's Bookstore example keeps
track of the books that a user has ordered within an object. The object is type
ShoppingCart and each book that a user orders is stored in the shopping cart as
a ShoppingCartItem object. For example, the following comes from further down
in the doGet method of the CatalogServlet:
public
void doGet (HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
HttpSession
session = request.getSession(true);
ShoppingCart
cart = (ShoppingCart)session.getValue(session.getId());
...
// Check
for pending adds to the shopping cart String bookId =
request.getParameter("Buy");
//If the
user wants to add a book, add it and print the result String bookToAdd =
request.getParameter("Buy"); if (bookToAdd != null) {
BookDetails
book = database.getBookDetails(bookToAdd);
cart.add(bookToAdd, book); out.println("<p><h3>" +
...);
}
}
Invalidating the Session
A user's
session can be invalidated manually or, depending on where the servlet is
running, automatically. (For example, the Java Web Server automatically
invalidates a session when there have been no page requests in some period of
time, 30 minutes by default.) To invalidate a session means to remove the
HttpSession object and its values from the system.To manually invalidate a
session, use the session's invalidate method.
public
class ReceiptServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
...
scart =
(ShoppingCart)session.getValue(session.getId());
...
// Clear out
shopping cart by invalidating the session session.invalidate();
// set
content type header before accessing the Writer
response.setContentType("text/html");
out = response.getWriter();
...
}
}
Methods
1. public
void setAttribute(java.lang.String
name, java.lang.Object value)
Binds an
object to this session, using the name specified. If an object of the same name
is already bound to the session, the object is replaced.
2. public
java.lang.Object getAttribute(java.lang.String
name)
Returns
the object bound with the specified name in this session, or null if no object
is bound under the name
3. public
java.util.Enumeration getAttributeNames()
An
Enumeration of String objects containing the names of all the objects bound to
this
session.
4. public
void removeAttribute(java.lang.String
name)
Removes
the object bound with the specified name from this session. If the session does
not have an object bound with the specified name, this method does nothing.
5. public
long getCreationTime()
Returns
the time when this session was created, measured in milliseconds
6. public
long getLastAccessedTime()
Returns
the last time the client sent a request associated with this session, as the
number of milliseconds since midnight January 1, 1970 GMT, and marked by the
time the container recieved the request.
7. public
int getMaxInactiveInterval()
Returns
the maximum time interval, in seconds, that the servlet container will keep this
session open between client accesses. After this interval, the servlet
container will invalidate the session. A negative time indicates the session
should never timeout.
8. public
void setMaxInactiveInterval(int
interval)
Specifies
the time, in seconds, between client requests before the servlet container will
invalidate this session. A negative time indicates the session should never
timeout
9. public
void invalidate()
Invalidates
this session then unbinds any objects bound to it.
10.
public java.lang.String getId()
Returns a
string containing the unique identifier assigned to this session. The
identifier is assigned by the servlet container.
Example:
Orderform.html
<HTML>
<HEAD>
<TITLE>Order Form</TITLE>
</HEAD>
<BODY >
<H1>Order
Form</H1>
<FORM
ACTION="show-items" METHOD="POST">
New Item
to Order:
<INPUT
TYPE="TEXT" NAME="newItem"
VALUE="CompleteRef"><P> <INPUT TYPE="SUBMIT"
VALUE="Order and Show All Purchases">
</FORM>
</BODY>
</HTML>
ShowItems.java
import
java.io.*; import javax.servlet.*;
import
javax.servlet.http.*; import java.util.*;
public
class ShowItems extends HttpServlet {
public void doPost (HttpServletRequest
request,HttpServletResponse response) throws ServletException, IOException {
HttpSession
session = request.getSession();
ArrayList
previousItems = (ArrayList)session.getAttribute("Items"); if
(previousItems == null) {
previousItems
= new ArrayList();
}
String
itemsVal = request.getParameter("newItem"); if (itemsVal != null) {
previousItems.add(items);
}
session.setAttribute("Items",
previousItems);
response.setContentType("text/html");
PrintWriter
out = response.getWriter();
out.println("<HTML>\n"
+
"<HEAD><TITLE>"
+ title + "</TITLE></HEAD>\n" + "<BODY
BGCOLOR=\"#FDF5E6\">\n" );
if (previousItems.size() == 0) { out.println("<I>No
items</I>");
} else { out.println("<UL>");
Enumeration
e = Collections.enumeration(previousItems); while(e.hasMoreElements())
out.println(e.nextElement());
out.println("</UL>");
}
out.println("</BODY></HTML>");
}
}
Session-tracking to keep per-client access counts import
java.io.*;
import
javax.servlet.*; import javax.servlet.http.*; import java.util.*;
public
class ShowSession extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
HttpSession session = request.getSession(); String heading;
Integer
accessCount = (Integer)session.getAttribute("Count"); if (accessCount
== null) {
accessCount
= new Integer(0); heading = "Welcome, Newcomer";
} else {
heading =
"Welcome Back";
accessCount
= new Integer(accessCount.intValue() + 1);
}
session.setAttribute("Count",
accessCount); PrintWriter out = response.getWriter(); String title =
"Session Tracking Example"; String docType
="<HTML>\n" +
"<HEAD><TITLE>"
+ title + "</TITLE></HEAD>\n" + "<BODY
BGCOLOR=\"#FDF5E6\">\n" +
"<H2>Information
on Your Session:</H2>\n" + "<TABLE BORDER=1>\n" +
"<TR
>\n" +"<TH>Info Type<TH>Value\n" +
"<TR>\n" +
"<TD>ID\n" +" <TD>" + session.getId() +
"\n" + "<TR>\n" +" <TD>Creation
Time\n"+"
<TD>" +new
Date(session.getCreationTime()) + "\n" + "<TR>\n" +
"<TD>Time of Last Access\n" +
"<TD>"+new
Date(session.getLastAccessedTime()) + "\n" + "<TR>\n"
+ "<TD>Number of Previous Accesses\n" +
"<TD>" + accessCount + "\n" + "</TABLE>\n" + </BODY></HTML>");
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.