HttpSession Interface:-


As we already know that HTTP is a stateless protocol, so it does not have any means for web server to identify multiple client requests (i.e. web server cannot know whether client made a request before too or not).
Java solve this problem by introducing HttpSession. Web container uses HttpSession to identify client requests across multiple client requests.
A session is a name(String)/value(Object) pair, stored at the server side.
Web container creates a separate session for each client, and it exists for a time specified by you at the time of creating session. We can use sessions to store all the information, we get back from client in all the requests made by him during a session.



Whenever client made a request for the first time, web container automatically creates a unique sessions ID (called JSessionID) for each client, that is used to identify clients across multiple requests.
Container creates a Cookie, embed the session ID in that and send back to the client as a part of server response. Whenever client makes subsequent requests, he also sends its session ID with request. Container sees the session ID to identify the client.

Getting a reference to HttpSession -

We can get a reference to HttpSession by using one of the following methods of HttpServletRequest-
1 - HttpSession getSession() - This method creates a new HttpSession if there is no session exists previously.
, or returns the existing session otherwise.
HttpSession session = request.getSession()

Where request is a HttpServletRequest.
2- HttpSession getSession(boolean state) - This method can do one of the following thing depending upon state value -
a- If state is set to false - It will return you existing HttpSession. If no session exists previously, it will not create any new session and returns null.
b- If state is set to true - It will return you existing session or create a new session if session does not exists previously.
HttpSession session = request.getSession(true/false);

Where request belongs to HttpServletRequest.

HttpSession Methods -

Some important methods of HttpSession are as follows -
Method name with return type Description
1- void setAttribute(String Attribute_name, Object Attribute_value) - This method is used to add an attribute to session, whose name and value are specified by Attribute_name and Attribute_value. If attribute of the same name exists previously in session, then it will replace the old value of attribute with this new value.
2- Object getAttribute(String Attribute_name) This method returns the value of attribute as Object, whose name is specified by Attribute_name.
3- java.util.Enumeration getAttributeNames() This method returns all attribute names of current session as Enumeration of String type.
4- String getId() This method returns the ID (unique identifier of session)associated with servlet. The session ID is created by web container..
5- long getCreationTime() This method returns the creation time of session. Time measured in millisecond since midnight of January 1, 1970.
6- long getLastAccessedTime() This method returns the last accessed time of session by client. Time measured in millisecond since midnight of January 1, 1970.
7- void setMaxInactiveInterval(int expiry_time) This method is used to set the time interval, after which session will expires. Where expiry_time is specified in seconds.
Note - If we specify negative expiry_time, session will never expires.
8- int getMaxInactiveInterval() This method returns the expiry_time of session in seconds specified by setMaxInactiveInterval(int expiry_time) method.
9- void invalidate() This method ends session and unbind all the attributes associated with it.
9- boolean isNew() This method is used to check whether session is previously existed session or a new one. It returns true if session is new one, or false otherwise.

Example 1 -

This basic example will show you how to create a session, check whether session is new or existing one, how to set expiry time for session, and how to get servlet creation and last accessed time.
And finally we will see that container creates a unique session for each client, when client makes first request.
1- index.html or index.jsp - This will be your default page.
<!DOCTYPE html>
<html>
    <head>
        <title>Session Demo</title>
    </head>
    <body>
        <a href="FirstServ">Click Here to show session information </a>
    </body>
</html>        

2- Create a package named servs and within servs create a servlet named FirstServ.
package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServ extends HttpServlet {

 public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try
        {
            PrintWriter out = response.getWriter();
            HttpSession session = request.getSession();
            if(session.isNew())  // checking whether session is new one or existing one.
            {
                out.println("This is new session");
            }
            else
            {
                out.println("This is previously existed session");
            }
            // Setting session timeout to one hour
            session.setMaxInactiveInterval(60*60);  // 60*60(seconds) = 1 hour

            // Getting session id, creation time and last accessed time.
            out.println("Session id is - "+ session.getId());
            out.println("Session creation time - "+ (new java.util.Date(session.getCreationTime())));
            out.println("Session last accessed time - "+ (new java.util.Date(session.getLastAccessedTime())));
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}    

3- web.xml -
<web-app>
    <servlet>
        <servlet-name>FirstServ</servlet-name>
        <servlet-class>servs.FirstServ</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>FirstServ</servlet-name>
        <url-pattern>/FirstServ</url-pattern>
    </servlet-mapping>
</web-app>  

4- Now run your project and it will show you the following output -



Copy the URL shown in URL box.
When you will click on the link, it will show you the session information as shown below -


Note the session id.

Now open some other web browser and paste the copied URL there. Again it will show you default page as follows -



When you will click on the link, it will show you the session information as shown below -


Note that here session id is different.

Note - Our local web container consider request from different web browser as requests from different clients.

Ending a session -

There are 3 ways a session can end -
1- The application shut down.
2- Session expiry time over.
3- You call invalidate() method

Setting session expiry time -

We can define same expiry time for all sessions in web app or define different expiry time for different session instances -
1- Setting same expiry time for all sessions -
If we want to set the same expiry time for all the sessions, we can define it in deployment descriptor (web.xml) as follows -
<web-app>
    <servlet>
        ......
    </servlet>
    <servlet-mapping>
        .......
    </servlet-mapping>


<session-config>
 <session-timeout>
   30    
<!--   
// note time is specified in minutes.
// If client does not make any request for 30 minutes, session will expire.
-->
</session-timeout>
</session-config>


</web-app> 
  

2- Setting different expiry time for different sessions -
We can define different expiry time for different sessions using setMaxInactiveInterval() method as follows -
session.setMaxInactiveInterval(60*30); // Note time is specified in second. 
// If client does not make any request for 30 minutes, this session will expire.     
Note -
If we deine the session expiry time in both ways, then second one has the priority i.e. session will expire depending upon the expiry time defined in setMaxInactiveInterval() method.

Example 2 -

In this example we will use session to identify subsequent client requests.
Example 2.1 - TO better understand why to use sessions, let us first see what problem will occur if we do not use session. index.html or index.jsp -
<!DOCTYPE html>
<html>
 <head>
   <title>HttpSessionDemo2</title>
 </head>
 <body>
      
  <form method="post" action="LoginCheck">
             
   <table border="1px">
     <tr>
       <td>User Name </td>
       <td><input type="text" name="t1" placeholder="Enter name"></td>
     </tr>
     <tr>
      <td>Password </td>
      <td><input type="password" name="t2" placeholder="Enter password"></td>
     </tr>
    <tr>
      <td><input type="submit" value="Login"></td>
      <td><input type="reset" value="Reset"></td>
    </tr>
    </table>
  
    </form>
    </body>
</html>    
2 - Create a package named servs and within servs create a servlets named LoginCheck and Home.
LoginCheck Servlet -
package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginCheck extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try
        {
            PrintWriter out = response.getWriter();
            String nm = request.getParameter("t1");
            String ps = request.getParameter("t2");
            if(nm.equals("admin") && ps.equals("123"))
            {
                response.sendRedirect("Home");
            }
            else
            {
                out.println("<h1 style='color:red'>Wrong user name or password</h1>");
                RequestDispatcher rdp = request.getRequestDispatcher("index.html");
                rdp.include(request, response);
            }
            
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}
        

Home Servlet -

package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Home extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try
        {
            PrintWriter out = response.getWriter();
            out.println("<h1 style='padding:10px'>Home Page</h1>");
            out.println("<hr>");
            out.println("Welcome to Home");
        } 
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }   
}
    

3- web.xml Add the following code to web.xml -
<web-app>
    <servlet>
        <servlet-name>LoginCheck</servlet-name>
        <servlet-class>servs.LoginCheck</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Home</servlet-name>
        <servlet-class>servs.Home</servlet-class>
    </servlet>
  
 <servlet-mapping>
        <servlet-name>LoginCheck</servlet-name>
        <url-pattern>/LoginCheck</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Home</servlet-name>
        <url-pattern>/Home</url-pattern>
    </servlet-mapping> 
</web-app>
        

4- Now run project, It will show you index.html page, enter username and password and click Login button -



If we enter correct user name and password(admin/123), it will display following output -



Now copy the url from web browser and open some other web browser and enter copied url there.


You will be surprised that without login we enter to Home page (i.e. Any user can enter to Home page just by knowing the URL of home page.).
To solve this problem we can use session.

Example 2.2 - To solve the above problem we can use Session as follows -
index.html or index.jsp -
<!DOCTYPE html>
<html>
 <head>
   <title>HttpSessionDemo2</title>
 </head>
 <body>
      
  <form method="post" action="LoginCheck">
             
   <table border="1px">
     <tr>
       <td>User Name </td>
       <td><input type="text" name="t1" placeholder="Enter name"></td>
     </tr>
     <tr>
      <td>Password </td>
      <td><input type="password" name="t2" placeholder="Enter password"></td>
     </tr>
    <tr>
      <td><input type="submit" value="Login"></td>
      <td><input type="reset" value="Reset"></td>
    </tr>
    </table>
  
    </form>
    </body>
</html>    
2 - Create a package named servs and within servs create following servlets -
LoginCheck Servlet -
package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginCheck extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try
        {
            PrintWriter out = response.getWriter();
            HttpSession session = request.getSession();
            String nm = request.getParameter("t1");
            String ps = request.getParameter("t2");
            if(nm.equals("admin") && ps.equals("123"))
            {
                session.setAttribute("Name", nm);
                response.sendRedirect("Home");
            }
            else
            {
                out.println("<h1 style='color:red'>Wrong user name or password</h1>");
                RequestDispatcher rdp = request.getRequestDispatcher("index.html");
                rdp.include(request, response);
            }
            
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}
        

Home Servlet -

package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Home extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try
        {
            HttpSession session = request.getSession();
            if(session.getAttribute("Name") == null)
            {
                response.sendRedirect("index.html");
            }
            PrintWriter out = response.getWriter();
            out.println("<h1 style='padding:10px'>Welcome to Home</h1>");
            out.println("<hr>");
            out.print("<a href='Gallery'>Gallery</a>");
            out.print("<a href='Logout'>Logout</a>");

        } 
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }   
}    

Gallery Servlet -
package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Gallery extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
      
        try
        {
            HttpSession session = request.getSession();
            if(session.getAttribute("Name") == null)
            {
                response.sendRedirect("index.html");
            }
            PrintWriter out = response.getWriter();
            out.println("<h1>Welcome to gallery</h1>");
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}    

Logout Servlet -
package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Logout extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       try
       {
           HttpSession session = request.getSession();
           session.invalidate();  // destroy all sessions and go back to Login form.
           response.sendRedirect("index.html");
       }
       catch(Exception ex)
       {
           System.out.println(ex);
       }
    }
}    

3- web.xml Add the following code to web.xml -
<web-app>
    <servlet>
        <servlet-name>LoginCheck</servlet-name>
        <servlet-class>servs.LoginCheck</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Home</servlet-name>
        <servlet-class>servs.Home</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Gallery</servlet-name>
        <servlet-class>servs.Gallery</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Logout</servlet-name>
        <servlet-class>servs.Logout</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginCheck</servlet-name>
        <url-pattern>/LoginCheck</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Home</servlet-name>
        <url-pattern>/Home</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Gallery</servlet-name>
        <url-pattern>/Gallery</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Logout</servlet-name>
        <url-pattern>/Logout</url-pattern>
    </servlet-mapping>
</web-app>        

4- Now run project, It will show you index.html page, enter username and password and click Login button -



If we enter correct user name and password(admin/123), it will display following output -



Now copy the url from web browser and open some other web browser and enter copied url there.


So now web container redirect us to login page if we want to enter to home page without proper login.