Lesson 5 | Maintaining state |
Objective | Write and execute a servlet that counts. |
Maintaining State and Counter using Java Servlet
Servlets are marvelous for maintaining state: is this user logged in? What has this customer ordered so far?
They do this with the help of a session object, which represents a single users interactions with the server at one time.
If I load ten or twelve pages from the same server in a short period of time, that is a single session, and servlets can easily keep track of information from page to page within that session. If I come back three days later, that is a different session.
If another user is requesting pages from the same server at the same time I am, that user has a different session.
Getting a Session Object
Very often, one servlet will save information about a user in a session, and another servlet will retrieve that information.
They do this by getting a session object, and calling its getValue()
and putValue()
methods.
These methods each take the value name, a simple string, as a parameter. For example, to save 500 as a session value called Limit, I would code:
session.putValue("Limit", new Integer(500));
You use an Integer
object rather than a simple int
value so that the session methods can determine and convert the type more easily.
To retrieve that limit from a session, within the same servlet or another, I would code:
Integer limit = (Integer) session.getValue("Limit");
int value = limit.intValue();
For either of these method calls to work, I need a session object. I get one from the HTTP request object that is passed to
doGet()
, like this:
HttpSession session = req.getSession(false);
The parameter to this call, false
, instructs getSession()
not to create a session if one does not exist already.
This call will return null
if no session exists. Heres a typical way to set your session object:
HttpSession session = req.getSession(false);
// declare variables to hold session values
if (session == null) {
session = req.getSession(true);
// initialize variables to default values
// store them in the session with session.putValue()
}
// get values with session.getValue()
The second call to getSession()
is passed true so that a new session will be created.
Review the HTML for forms in the next lesson.
Maintaining State - Exercise