Demonstrate session tracking - JSP Program

Q. Write a JSP application to demonstrate the session tracking.

Answer:

Session is basically a time frame and tracking means maintaining user data for certain period of time frame. Session TrackingĀ is a mechanism used by the web container to store session information for a particular user. It is used to recognize a particular user.

Below example shows how to use HttpSession object to find out creation time and last accessed time for a session.

SessionDemo.jsp

<%@ page import="java.io.*,java.util.*" %>
<%
   // Get session creation time.
   Date createTime = new Date(session.getCreationTime());
   // Get last access time of this web page.
   Date lastAccessTime = new Date(session.getLastAccessedTime());

   String title = "Welcome Back to my website";
   Integer visitCount = new Integer(0);
   String visitCountKey = new String("visitCount");
   String userIDKey = new String("userID");
   String userID = new String("Surendra");

   // Check if this is new comer on your web page.
   if (session.isNew())
   {
      title = "Welcome to my website";
      session.setAttribute(userIDKey, userID);
      session.setAttribute(visitCountKey,  visitCount);
   }
   visitCount = (Integer)session.getAttribute(visitCountKey);
   visitCount = visitCount + 1;
   userID = (String)session.getAttribute(userIDKey);
   session.setAttribute(visitCountKey,  visitCount);
%>
<html>
    <head>
        <title>Session Tracking</title>
    </head>
    <body>
        <center>
            <h1>Session Tracking Example</h1>
        </center>
        <table border="1" align="center">
            <tr bgcolor="#ffcccc">
                <th>Session info</th>
                <th>Value</th>
            </tr>
            <tr >
                <td>id</td>
                <td><% out.print( session.getId()); %></td>
            </tr>
            <tr>
                <td>Creation Time</td>
                <td><% out.print(createTime); %></td>
            </tr>
            <tr>
                <td>Time of Last Access</td>
                <td><% out.print(lastAccessTime); %></td>
            </tr>
            <tr>
                <td>User ID</td>
                <td><% out.print(userID); %></td>
            </tr>
            <tr>
                <td>Number of visits</td>
                <td><% out.print(visitCount); %></td>
            </tr>
        </table>
    </body>
</html>


web.xml

<web-app>
    <servlet>
        <servlet-name>xyz</servlet-name>
        <jsp-file>/SessionDemo.jsp</jsp-file>
    </servlet>
    <servlet-mapping>
        <servlet-name>xyz</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>
</web-app>


Output:

session tracking