Nearby lessons

17 of 34

Servlet - Session Management (Session API)

📌 What You Will Learn
  • 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 + sessionidSession

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.

Example03
JCode Cell
1 
2public HttpSession getSession()
3

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.

Example04
JCode Cell
1 
2public HttpSession getSession(boolean b)
3

Case Study

Un Forwar

d

Pw

d

Submit

Login.htmlValidateServletInboxServlet

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?

Example06
JCode Cell
1 
2HttpSession session =req.getSession(false);
3if(session==null)
4{
5forward request to login page
6}
7else
8{
9display inbox page
10}
11

Case Study

Answer: nd 3

Invalidating session object:

We can invalidate a session by using the following 2 ways

Example07
JCode Cell
1 
2session = req.getSession();
3session = req.getSession(false);
4session = req.getSession(true);
5session = resp.getSession();
6

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...

Example08
JCode Cell
1 
2By using invalidate() method
3By Timeout mechanism
4

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) ScopeIt is applicable only for a

It is applicable for all Sessions particular Session Object, on

Example09
JCode Cell
1 
2<web-app>
3...
4<session-config>
5<session-timeout>10</session-timeout>
6</session-config>
7</web-app>
8

Case Study

Minutes

Indicates that Session never

Indicates that Session neverexpires

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.

Example10
JCode Cell
1 
2Units which are created in that Web which we called this Method
30 Value Application Seconds
4-ve Value Sessions will expire immediately
5

Important Methods of HttpSession

To check whether the session object is newly created or not

Example11
JCode Cell
1 
2public boolean isNew()
3

Important Methods of HttpSession

to expire a session forcefully

Example12
JCode Cell
1 
2public void invalidate()
3

Important Methods of HttpSession

To set session timeout for a particular session object

Example13
JCode Cell
1 
2public void setMaxInactiveInterval(int seconds)
3

Important Methods of HttpSession

Returns the session timeout value in seconds

Example14
JCode Cell
1 
2public int getMaxInactiveInterval()
3

Important Methods of HttpSession

Returns session id

Example15
JCode Cell
1 
2public String getId()
3

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);

Example16
JCode Cell
1 
2public long getCreationTime()
3

Important Methods of HttpSession

Returns the time when the client accessed session recently in milli seconds since 1970 Jan 1st.

Example17
JCode Cell
1 
2public long getLastAccessedTime()
3

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.

Example18
JCode Cell
1 
2public ServletContext getServletContext()
3

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

Example19
JCode Cell
1 
2public void setAttribute(String name,Object value)
3public Object getAttribute(String name)
4public void removeAttribute(String name)
5public Enumeration getAttributeNames()
6

Demo Program for session management by using Session API

login.html:

Demo Program for session management by using Session API

Example21
JCode Cell
1 
2<html>
3<body>
4<form action="/session1/test1">
5<h1>Enter Books Information</h1>
6<pre>
7<h2>Name:<input type="text" name="name">
8Value:<input type="text" name="value">
9</h2></pre>
10 
11<input type="submit" value="Add To Cart"/>
12</form>
13<a href="/session1/test2">Show My Cart</a>
14</body>
15</html>
16

SessionServlet1.java

Example22
JCode Cell
1 
2import java.io.*;
3import javax.servlet.*;
4import javax.servlet.http.*;
5import javax.servlet.annotation.*;
6@WebServlet("/test1")
7public class SessionServlet1 extends HttpServlet
8{
9public void doGet(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException
10{
11PrintWriter out=resp.getWriter();
12HttpSession hs=req.getSession();
13if(hs.isNew())
14{
15out.println("<h2>New Session got created with session ID:"+hs.getId()+"</h2>");
16}
17else
18{
19out.println("<h2>Existing Session only using with session ID:"+hs.getId()+"</h2>");
20}
21String name=req.getParameter("name");
22String value=req.getParameter("value");
23hs.setAttribute(name,value);
24//hs.setMaxInactiveInterval(120);
25RequestDispatcher rd = req.getRequestDispatcher("login.html");
26rd.include(req,resp);
27}
28}
29

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=12345Session

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:

Example23
JCode Cell
1 
2import java.io.*;
3import javax.servlet.*;
4import javax.servlet.http.*;
5import java.util.*;
6import javax.servlet.annotation.*;
7@WebServlet("/test1")
8public class SessionServlet2 extends HttpServlet
9{
10public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
11{
12PrintWriter out=res.getWriter();
13HttpSession hs=req.getSession(false);
14if(hs == null)
15{
16out.println("<h2> No session information is available</h2>");
17}
18else
19{
20Enumeration e = hs.getAttributeNames();
21out.println("<table border=2><tr><th>Session AttributeName</th><th>Sesion Attribute value</th></tr>");
22while(e.hasMoreElements())
23{
24String name = (String)e.nextElement();
25String value = (String)hs.getAttribute(name);
26out.println("<tr><td>"+name+"</td><td>"+value+"</td></tr>");
27}
28out.println("</table>");
29long l1 = hs.getCreationTime();
30long l2 = hs.getLastAccessedTime();
31int l3 = hs.getMaxInactiveInterval();
32out.println("<h3>The creation time is "+new Date(l1)+"</h3>");
33out.println("<h3>The last accessed time is "+new Date(l2)+"</h3>");
34out.println("<h3>Max inactive interval is :"+l3+"</h3>");
35}
36}
37}
38

SessionServlet2.java

Example24
JCode Cell
1 
2<html>
3<body>
4<form action="/session2/test1">
5<h1>Enter session information</h1>
6<pre>
7<h2>Name:<input type="text" name="uname">
8Value:<input type="text" name="uvalue">
9</h2></pre>
10 
11<input type="submit"/>
12</form>
13<a href="/session2/test2">RequestHeader Information</a>
14</body>
15</html>
16

SessionServlet1.java

Example25
JCode Cell
1 
2import java.io.*;
3import javax.servlet.*;
4import javax.servlet.http.*;
5import javax.servlet.annotation.*;
6@WebServlet("/test1")
7public class SessionServlet1 extends HttpServlet
8{
9public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
10{
11PrintWriter out=res.getWriter();
12HttpSession hs=req.getSession();
13if(hs.isNew())
14{
15out.println("<h2>New Session got created with session ID:"+hs.getId()+"</h2>");
16}
17else
18{
19out.println("<h2>Existing Session only using with session ID:"+hs.getId()+"</h2>");
20}
21String name=req.getParameter("uname");
22String value=req.getParameter("uvalue");
23hs.setAttribute(name,value);
24//hs.setMaxInactiveInterval(120);
25RequestDispatcher rd = req.getRequestDispatcher("login.html");
26rd.include(req,res);
27}
28}
29

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.

Example26
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5import java.util.*;
6import javax.servlet.annotation.*;
7@WebServlet("/test2")
8public class RequestHeaderDemoServlet extends HttpServlet
9{
10public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
11{
12PrintWriter out = resp.getWriter();
13out.println("<h1>Request Headers Information</h1></hr>");
14out.println("<table border=2><tr><th>HeaderName</th><th>Header values</th></tr>");
15Enumeration e = req.getHeaderNames();
16while(e.hasMoreElements())
17{
18String hname = (String)e.nextElement();
19out.println("<tr><td>"+hname+"</td><td>"+ req.getHeader(hname)+"</td></tr>");
20}
21out.println("</table></body></html>");
22}
23}
24
📝 Key Takeaways
  • Key ideas of Servlet - Session Management (Session API) explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3