Nearby lessons
17 of 34Servlet - Session Management (Session API)
- Understand Unit 4: Session Management
- Understand Session Management by using Session API
- Understand Study
- Understand Important Methods of HttpSession
- See complete working code examples
Session Management (Session API) is an essential part of the Java Servlet technology. This lesson explains Unit 4: Session Management, Session Management by using Session API and Study with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid.
Unit 4: Session Management
Objective:
- For the given scenario, describe the session API?
- Explain the process of creating a Session Object?
3.What are various different mechanisms to invalidate a session?
Client and Server can communicates with some common language, which is nothing but HTTP.
The basic limitation of HTTP is, it is stateless protocol. i.e it is unable to remember client
information for future purpose across multiple requests.Every request to the server is treated as a
new request.
Hence some mechanism is required at server side to remember client information across multiple
requests. This mechanism is nothing but session management mechanism.
The following are various session management mechanisms.
- Session API
- Cookies
- URL Rewriting
- Hidden Form Fields [It is not official mechanism from SUN,it is just programmer's trick to
remember client information]
Session Management by using Session API
req 1
| resp 1 + sessionid | Session |
|---|
Object
req 2 + sessionid
Client : Server
:
:
Whenever client sends a request to the server, if server wants to remember client information for
the future purpose then server will create a session object and stores the required information in
the form of attributes.Server sends the corresponding session id to the browser as the part of
response.
With every consecutive request,browser sends that session id. By accessing session id and the
corresponding session object,server can able to remember client info across multiple requests.
Client information will be maintained at server side in session object in the form of attributes.
Process of Creating Session Object:
HttpServletRequest interface defines the following methods for creating session object.
Session Management by using Session API
Eg: HttpSession session = req.getSession();
First this method will check is there any session aleady associated with request object or not.
If the request does not associated with any session, then this method creates a new session object
and returns it.
If the request already associated with session object then existing session object will be returned.
There is a guarentee that this method will always return session object.It may be newly created or
already existing one.
Session Management by using Session API
If the argument is true then this method simply acts as getSession().
If the argument is false, then this method first checks whether the request associated with any
session or not.If the request already associated with session then this method returns existing
session object.
If the request does not associated with any session then this method returns null without creating
any new session object.
Case Study
Un Forwar
d
Pw
d
Submit
| Login.html | ValidateServlet | InboxServlet |
|---|
ValidateServlet will check whether credentials are valid or not. If valid then it is responsible to
create session object. Hence inside ValidateServlet we have to use getSession() method.
HttpSession session =req.getSession();
After creating session object ValidateServlet forwards the request to InboxServlet.
To Access InboxServlet compulsory the request should be associated with session. If the request
does not associated with any session, then it is not responsible to create session object and it will
forward the request to login page. Hence in this case we have to use getSession(false)
Case Study
Q. Which of the following are equal?
Case Study
Answer: nd 3
Invalidating session object:
We can invalidate a session by using the following 2 ways
Case Study
invalidate() method:
HttpSession interface defines invalidate() method to invalidate session explicitly.
public void invalidate()
whenever we are clicking logout button internally this method will be executed.
session.invalidate()
- Timeout mechanism:
If we are not performing any operation on the session object for a pre defined amount of time
then the session will be expired automatically. This predefined amount of time is called session
timeout.
We can configure session timeout either server level or web application level or a particular
session object level.
- Session Timeout at Server Level:
Most of the web servers provide default support for session timeout. Mostly it is 30 minutes.
We are allowed to change this server level session timeout based on our requirement.
This session timeout applicable for all sessions created in that server of all web applications.
- Configuring session timeout at web application level:
If we are not satisfied with server level session timeout then we have to configure at application
level.
We can configure session time out at application level in web.xml as follows...
Case Study
<session-config> is the child tag of <web-app> and hence we can place anywhere within
<web-app>
The unit to the <session-timeout> is minutes
zero or -ve value indicates that session never expires.
This session timeout is applicable for all the session s which are created in that web application.
- Setting session timeout for a particular session object:
We can set session timeout for a particular session object by using the following method of
HttpSession.
public void setMaxInactiveInterval(int seconds)
The argument is in seconds
-ve value indicates that session never expires
zero value indicates that session will expire immediately.
This session timeout is applicable only for a particular session object on which we call this method.
Comparison between 2 Session Timeout Mechanisms:
| Property | <session-timeout> | setMaxInactiveInterval() |
|---|---|---|
| 1) Scope | It is applicable only for a |
It is applicable for all Sessions particular Session Object, on
Case Study
Minutes
Indicates that Session never
| Indicates that Session never | expires |
|---|
expires
Indicates that Session never
expires
Q. How we can implement Log out mechanism?
2 ways.
1st way:
session.invalidate();
2nd way:
session.setMaxInactiveInterval(0);
public class LogOutServlet extends HttpServlet
{
doGet(..)...
{
HttpSession session = req.getSession(false);
if(session != null)
{
session.invalidate();
}
}
}
Note:
If we configured session timeout in all 3 ways then timeout at particular session object will be
considered.
Important Methods of HttpSession
To check whether the session object is newly created or not
Important Methods of HttpSession
to expire a session forcefully
Important Methods of HttpSession
To set session timeout for a particular session object
Important Methods of HttpSession
Returns the session timeout value in seconds
Important Methods of HttpSession
Returns session id
Important Methods of HttpSession
Returns the time when the session was created in milli seconds since Jan 1st 1970.
If we are passing this long value to the Date constructor then we will get exact Date and time.
Eg:
long ms = session.getCreationTime();
Date d = new Date(ms);
SOP(d);
Important Methods of HttpSession
Returns the time when the client accessed session recently in milli seconds since 1970 Jan 1st.
Important Methods of HttpSession
Returns the ServletContext object to which this session belongs
HttpSession interface defines the following methods to perform attribute management in session
scope.
Important Methods of HttpSession
Note: Once session expired,we are not allowed to call most of above methods.Otherwise we will
get RE saying IllegalStateException
Demo Program for session management by using Session API
login.html:
Demo Program for session management by using Session API
SessionServlet1.java
SessionServlet2.java
session1
|-login.html
|-WEB-INF
|-classes
|-SessionServlet1.class
|-SessionServlet2.class
How the session id exchanging b/w Client and Server:
req 1
| resp 1 + set-cookie:JSESSIONID=12345 | Session |
|---|
Object
req 2 + cookie:JSESSIONID=12345
Client : Server
:
:
Whenever browser sends a request to server,If server wants to remember client information for
the future purpose,then Server will create Session object and store required information in the
form of attributes.Server sends the corresponding sessionid as the part of response.For this server
will use setCookie response header.
Browser will retrieve that session id and will send with every consecutive request to the
server.For this browser will use cookie request header.
Hence session id exchanging b/w client and server with setCookie response header and cookie
request header.
Demo Program to demonstrate how session id is exchanging b/w client and server:
login.html:
SessionServlet2.java
SessionServlet1.java
RequestHeaderDemoServlet.java
session2
|-login.html
|-WEB-INF
|-classes
|-SessionServlet1.class
|-RequestHeaderDemoServlet.class
Note:
If the required session information is very less then creating a separate session object and
maintaining that object at server side is not recommended because it creates performance problems.
To resolve this,we should go for Cookies concept,where session information is maintained at client
side & server is not responsible to maintain session info.
- Key ideas of Servlet - Session Management (Session API) explained simply
- Ready-to-use code examples
- Exam-style questions at the end