Session Tracking Using The HttpSession Interface In Servlets

Introduction

 
Session tracking is very important as it helps to keep track of requests from the same client. One of the best examples of session tracking is an online shopping cart. In online shopping carts, it is absolutely necessary to remember requests from the same client. This can be done only if the website can track the session of the client.
 
HttpSession interface helps in identifying users in a multi-page request scenario and in providing information about that user. The HttpSession interface is used to create a session between the client and server. The session is created between an HTTP Client and an HTTP Server by the servlet container using this interface.
 
The Java Web Server keeps track of each user on the site by creating a session object of interface HttpSession.
 
For Example,
  1. package session;  
  2. import java.io.*;  
  3. import java.util.Date;  
  4. import javax.servlet.*;  
  5. import javax.servlet.http.*;  
  6. public class SessionServlet extends HttpServlet {  
  7.     /* processes requests for both HTTP GET method */  
  8.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  9.         response.setContentType("text/html;charset=UTF-8");  
  10.         PrintWriter out = response.getWriter();  
  11.         HttpSession session = request.getSession();  
  12.         out.println("<html>");  
  13.         out.println("<head>");  
  14.         out.println("<title>Servlet SessionServlet</title>");  
  15.         out.println("</head>");  
  16.         out.println("<body>");  
  17.         out.println("<h1>SessionServlet at" + request.getContextPath() + "</h1>");  
  18.         out.println("Session Status: <br/>");  
  19.         if (session.isNew()) {  
  20.             out.println("New session created...<br/>");  
  21.         } else {  
  22.             out.println("Old session....<br/>");  
  23.         }  
  24.         out.println("<br/> Session id : " + session.getId());  
  25.         out.println("<br/> Creation time :");  
  26.         out.println(new Date(session.getCreationTime()));  
  27.         out.println("<br/>Last Accessed :");  
  28.         out.println(new Date(session.getLastAccessedTime()));  
  29.         out.println("</body>");  
  30.         out.println("</html>");  
  31.         out.close();  
  32.     }  
  33.     /* Return a short decription of the servlet */  
  34.     public String getServletInfo() {  
  35.         return "Short Description";  
  36.     }  
  37. }  

Storing Information in a Session

 
The data can be stored in an HttpSession object using the name=value pairs. The data which is stored, is available throughout the session. To store the data in a session , the method setAttribute() is used. The setAttribute() method sets the value of the attribute, which can be retrieved later by the request.
  1. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  2.     //get current session, or create  a new one if it doesn't exist.    
  3.     HttpSession httpSession = request.getSession(true);  
  4.     If(httpSession.isNew()) {  
  5.         httpSession.setAttribute("bgcolor""#FFFFFF");  
  6.         httpSession.setAttribute("name""Ashish");  
  7.         httpSession.setAttribute("shopping_cart", shopCart);  
  8.     }  
  9. }  

Retrieving Information Stored in Session

 
Session tracking can be done by the server using the HttpSession interface also. The previously stored value can be retrieved by using getAttribute() method. The session object will be available to all of the servlets and JSP’s that the user accesses until the session is closed due to timeout or error.
  1. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  2.     HttpSession httpSession = request.getSession(true);  
  3.     int i;  
  4.     Integer D = (Integer) session.getAttribute("Democounter");  
  5.     if (D == null) {  
  6.         i = 0;  
  7.     } else {  
  8.         i = D.intValue();  
  9.     }  
  10.     i++;  
  11.     Integer D2 = new Integer(i);  
  12.     session.setAttribute("counter", D2);  
  13.     PrintWriter out = response.getWriter();  
  14.     out.write("You've visited " + i + " times.");  
  15. }  

Invalidating a Session

 
If there is the prolonged moment of inactivity or there is no page request , the session might get invalidated. In case of the breach or intrusion then also the session can be invalidated. To invalidate a session means to remove the HttpSession object and its value from the system.
  1. String scart=(String)session.getValue(session.getId());    
  2. //clear out shopping cart by invalidating the session    
  3. session.invalidate();   

Session Timeout

 
Session Timeout is necessary as a session utilizes the memory locations to store information and long period of inactivity will occupy the memory unnecessarily. After a certain time period of inactivity the session is destroyed to prevent the number of sessions increasing infinitely. The data stored in the session disappears . Session timeout happens if the user remains inactive for a period greater than the set inactive time period.
 
The session timeout period can be set either in web.xml file or can be set by the method setMaxInactiveInterval(). This method is used to specify the time between the requests from the client before servlet container invalidates the session.
  1. <session-config>    
  2. <session-timeout>N</session-timeout>    
  3. <.session-config>   
This code shows the configuration tag that need to be written in web.xml file. In this code, N in the fragment is session timeout period.
 

Summary

 
Session tracking allows the server to keep track of successive requests made by the same client. The session is created between an HTTP client and an HTTP server by the servlet container using HttpSession. When the user makes a request, the server assigns it a session object and a unique session ID thereby helping in session tracking.