You are on page 1of 31

State Management

in Web Application
Servlet life cycle: a quick review
Servlet life cycle: a quick review
Each request runs in a separate thread
The Container runs multiple threads to process
multiple requests to a single servlet.
ServletRequest interface
Storing state information
How can he track the clients answers
Use a stateful session enterprise javabean
Use a database
Use an HttpSession
How sessions work
How sessions work
The client needs a unique session ID
How do the Client and Container
exchange Session ID info?
Container does virtually all the cookie
Container takes care of
generating the session ID,
creating a new Cookie object,
stuffing the session ID into the cookie,
set the cookie as part of the response.
on subsequent requests, the Container gets the session ID
from a cookie in the request, matches the session ID with an
existing session, and associates that session with the current
Check for the session already existed or
was just created
What if I want ONLY a pre-existing
How to use sessions if the client doesnt
accept cookies
If the client wont take cookies, you can use URL
rewriting as a back- up.
How to use sessions if the client doesnt
accept cookies
URL rewriting kicks in ONLY if cookies fail, and ONLY if
you tell the response to encode the URL
Inactive sessions
The HttpSession interface
Ways a session can die
3. The application goes
down (crashes or is

4. Call Invalidate() method

Can I use cookies for other things, or are
they only for sessions?
Although cookies were originally designed to help
support session state, you can use custom cookies for
other things. Remember, a cookie is nothing more than
a little piece of data (a name/value String pair)
exchanged between the client and server.
By default, a cookie lives only as long as a session
Using Cookies with the Servlet API
Using Cookies with the Servlet API
Key milestones for an HttpSession
Session lifecycle Events
for example, your attribute wants to know when its added to a session so that it
can synchronize itself with an underlying database (and update the database
when its removed from a session).
Session migration
In a clustered environment, the Container might do load-balancing by
taking client requests and sending them out to JVMs (which may or may
not be on different physical boxes, but that doesnt matter to us).
Session migration
Session migration
Session- related Listeners
Session-related Event Listeners and Event
Objects API overview
Keep state information in the query
Encode the state in the query string
Limited size
Keep state information in form fields