The Session Object
April 5, 2000
As we all know there are three commonly used 'ways' of
maintaining 'state' with the stateless HTTP protocol. Cookies,
URL re-writing and Hidden form fields in the HTML form. Session
object or the session tracking API isolates the programmer from
these implementation details. Although the actual implementation
may be server dependant theoretically:
- The client request a particular page
- The server 'creates a session' with this client (by either sending a cookie with the session id or URL re-writing etc.).
- Every time the same client (identified by the cookie or URL) comes back to the server, the server uses this session id to provide a facility to 'put' and 'get' some session dependant information.
- This information can be accessed till the session is not: invalidated or timed out.
Servlet API makes the session tracking very simple.
In your code you can 'get' a session object associated with every
user by :
HttpSession currSession = request.getSession(flag);
Where request is the HttpServletRequest object and flag is a
boolean variable.
- When flag = true - A new session object is created for this user
request.
- When flag = false - This method returns the already created
session object.
(Here the server uses the session ID it stored in the cookie
or URL to identify the session Object).
To add any session variables we call:
currSession.putValue("userName", Name);
This call will put the Name variable in the userName session
value. (Note: it actually will put a reference and hence you can
'put' objects in the 'session').
To access a previously stored session variable:
String storedName = currSession.getValue("userName");
We will write a simple web application which uses session values.
But before that let's look at one more class in this package:
RequestDispatcher.
Java Server Pages
Building Web Applications Using Servlets and JSP
Request Dispatcher
|