Nearby lessons
32 of 34Servlet - Examples: Session Management
- See complete runnable servlet programs
- Understand the output of each program
- Copy and deploy programs in Tomcat
Session management programs using Session API, Cookies, URL Rewriting, and Hidden Form Fields.
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
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
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 seperate session object and
maintaining that object at server side is not recommended b'z 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.
Session Management by using Cookies
returns the name of the Cookie
Session Management by using Cookies
returns the value of the Cookie
Session Management by using Cookies
Returns the max age of the Cookie in seconds.
Session Management by using Cookies
To set max age of the cookie.
setting max age as -1,then cookies will be expired automatically whenever browser window
closed.
-1 is the default value.
Demo Program for session Management by using Cookies
CookieDemoServlet1.java
CookieDemoServlet2.java
session3
|-cookie.html
|-WEB-INF
|-classes
|-CookieDemoServlet1.class
|-CookieDemoServlet2.class
Demo Program how cookies are exchanging b/w client and server
CookieDemoServlet1.java
Demo Program how cookies are exchanging b/w client and server
RequestHeaderDemoServlet.java
session4
|-cookie.html
|-WEB-INF
|-classes
|-CookieDemoServlet1.class
|-RequestHeaderDemoServlet.class
Persistant cookies vs non-persistant cookies:
If we are setting max age to the cookie,then such type of cookies are called persistant cookies or
permanent cookies. These will be stored in the local file system of the client.
If we are not setting max age ,then such type of cookies are called temporary cookies or non-
persistant cookies.These cookies will be stored in the browser's cache and not visible in the local
file system. Once we close the browser, automatically these cookies will be expired.
Advantages of Cookies:
- Very easy to implement
- Persist across server restarts also
- All browsers and servers provide automatic support for cookies.
Disadvantages of Cookies:
- Cookies can be enabled or disabled at client side to meet security constraints.
If the cookies are disabled then session management by using cookies is not possible.
2.The number of cookies supported by any browser is always fixed.
- The max size of the cookie is also fixed. Hence we can not store huge amount of information by
using Cookies.
- Cookie data is always String type.
Differences b/w Session API and Cookies:
| Session API | Cookies |
|---|---|
| 1) Session Information will be maintained at | 1) Session Information will be maintained at |
| Server side. | Client side. |
| 2) Best suitable if we want to store huge | 2) Best suitable if we want to store less amount |
| amount of Information. | of Information. |
RequestHeaderDemoServlet.java
If Cookies are disabled at Client Side then what will happend?
If the cookies are disabled at client side then browser is unable to see Set-Cookie response header.
Hence browser wont get any cookies or session id send by server.
If the cookies are disabled at client side then browser unable to send Cookie request header.Hence
server wont get any cookies or session id from the request and every request is treated as new
request. Due to this total session management fails.
To overcome this problem,we should go for the most powerful and painful technique: URL
REWRITING.
Session Management by URL REWRITING
URLs can be re written or encoded to include session information.This technique is called url
rewriting.
URL Rewriting=URL+Session Info
Eg: url;JSESSIONID=1234
HttpServletResponse defines the following methods to append session id to the url.
RequestHeaderDemoServlet.java
Returns url by appending JSESSIONID.
RequestHeaderDemoServlet.java
Returns url by appending session id.
This can be used as argument to sendRedirect() method.
The above 2 methods will append JSESSIONID to the url iff cookies are disabled at client side.
If the cookies are enabled,these methods return the same url without appending JSESSIONID.
At server side we can identify whether sessionid is coming as the part of url or from the Cookie
request header by using the following methods of HttpServletRequest.
RequestHeaderDemoServlet.java
By using these methods we can identify underlying session management technique.
Demo Program for session management by url rewriting
SessionServlet1.java
SessionServlet2.java
session5
|-login.html
|-WEB-INF
|-classes
|-SessionServlet1.class
|-SessionServlet2.class
Advantages of URL Rewriting:
There is no chance of disabling url rewriting technique. Hence it will work always.
Limitations of URL Rewriting:
1.It is very difficult to rewrite all urls to append session information.Hence it is the most painful
technique.
2.URL Rewriting will work only for dynamic documents.
Session Management by using Hidden Form Fields
It is not official technique from SUN Micro Systems.It is just Programmer's trick to remember client
information.
In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of an
user.
In such case, we store the information in the hidden field, which is required for future purpose.
We can declare hidden form field as follows..
<input type="hidden" name="uname" value="chitu">
Advantage of Hidden Form Field
It will always work whether cookie is disabled or not.
Disadvantage of Hidden Form Field:
- It is maintained at server side.
- Extra form submission is required on each page.
- Session information should be text data
Demo Program for session management by hidden form fields
SessionServlet1.java
SessionServlet2.java
SessionServlet3.java
throws ServletException,IOException
SessionServlet3.java
session7
|-login.html
|-WEB-INF
|-classes
|-SessionServlet1.class
|-SessionServlet2.class
|-SessionServlet3.class
Listeners
Objective:
- Describe web container event life cycle model for the request,session and web application.
2.Create and configure Listener class for each scope
3.Create and configure attribute listener for each scope
4.For the given scenario identify proper attribute listener?
In the web application there may be a chance of occuring several events like
Request object creation
Request object Destruction
Session object creation
Session object Destruction
Context object creation
Context object destruction
Attribute addition in request scope
Attribute Removal in request scope
Attribute Replacement in request scope
.....
whenever these events occur,if we want to do particular operation automatically then we should
go for listeners.
i.e Listener listens the events and will perform certain operations automatically.
All Listeners are divided into 3 groups
- Request Listeners:
These listen events related to request.
There are 2 types of Request Listeners
- ServletRequestListener
- ServletRequestAttributeListener
- Session Listeners:
These listen the events related to session. There are 4 types of session listeners.
- HttpSessionListener
- HttpSessionAttributeListener
- HttpSessionBindingListener
- HttpSessionActivationListener
- Context Listeners:
These listen events related to context.
There are 2 types of context listeners
SessionServlet3.java
This listener listens life cycle events of request object like creation and destruction.
This interface defines the following 2 methods.
1.public void requestInitialized(ServletRequestEvent e)
This method will be executed automatically at the tine of request object creation. i.e just before
starting service() method.
SessionServlet3.java
This method will be executed automatically at the time of request object destruction. ie just
after completing service() method.
- Every example is complete and compiles as-is
- Examples are grouped by topic
- Typing programs is the fastest way to learn servlets