by Dinesh Thakur Category: Session And Cookies

HTTP is a stateless protocol; each time a client requests for a page, a separate connection is established between the client and the server. Thus, it provides no way for a server to maintain information for a particular user across multiple requests. There are many web applications where it is required to maintain this information. For example, in case of shopping cart, it is required to keep track of the list of items that are added in each user's cart. For this, the server must provide a way to store data for each client and distinguish clients from one another.

Session provides such mechanism. A session consists of all the requests that are made during invocation of a single browser. The servlet manages the session using HttpSession interface. Using this interface, a session can be created between an HTTP client and an HTTP server. This session exists for a specified period of time across a sequence of requests from a user.

A servlet to keep track of the number of times a user has visited a site during the current session using interface HttpSession

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.util.*;

public class SessionTrackingExample extends HttpServlet

{

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

   {

       HttpSession session= request.getSession(true);

       // Create a session object if does not exist

       Date createTime =new Date(session.getCreationTime());

       // Get session creation time

       Date lastAccessTime = new Date(session.getLastAccessedTime());

       // Get sessions last access time

       String title = "Welcome Back !";

       Integer visitCounter =new Integer(0);

       String userID =new String("xyz");

       if (session.isNew())

          {

               title= "Welcome !";

               session.setAttribute("userID", userID);

          }

          else

             {

                 visitCounter = (Integer) session.getAttribute("visitCount");

                 visitCounter = visitCounter + 1;

                 userID = (String)session.getAttribute("userID");

             }

             session.setAttribute("visitCount", visitCounter);

             // Check if this is new Visitor

             response.setContentType("text/html");

             PrintWriter out= response.getWriter();

             out.println("<html>\n" +"<head><title>" + title+

             "</title></head>\n" + "<body\">\n" +

             "<h1 align=\"center \">"+title + "</h1>\n" +

             "<h2 align=\"center\">Session Details</h2>\n" +

             "<table border=\"1\" align=\"center\">\n" + 

             "<tr\">\n" +

             "<th>Session info</th><th>value</th></tr>\n"+

             "<tr>\n" + " <td>Id</td>\n" +

             "<td>" + session.getId() + "</td></tr>\n" +

             "<tr>\n" +" <td>Session Creation Time</td>\n" +

             "<td>" + createTime + " </td></tr>\n" +

             "<tr>\n" + " <td>Last Accessed at</td>\n" +

             "<td>" + lastAccessTime + " </td></tr>\n" +

             "<tr>\n" + " <td>Visitor ID</td>\n" +

             "<td>" + userID + " </td></tr>\n" +

             "<tr>\n" + " <td>Number of visits</td>\n" +

             "<td>" + visitCounter + "</td></tr>\n" + 

             "</table>\n" + "</body></html>");

     }

}

In this example, a session is created using the getSession () method of HttpServletRequest interface. The single parameter to this method indicates that a new session must be created if it does not exist. This method returns an HttpSession object. To access the properties of session including the session identifier, different methods, namely, getCreationTime(), lastAccessTime(), SetAttribute(), getAttribute(), and get Id ()are invoked using the session object.

Compile the servlet SessionTrackingExample and create appropriate entry in web.xml file. Type the URL http://localhost:8080/SessionTrackingExample in the browser. On first run, it will display the output shown in Figure

               Output Generated by SessionTrackingExample Servlet





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.