Track user's session using 'session' object in JSP


 

Track user's session using 'session' object in JSP

This section is about tracking user identity across different JSP pages using 'session' object.

This section is about tracking user identity across different JSP pages using 'session' object.

Track user's session using 'session' object in JSP

This section is about tracking user identity across different JSP pages using 'session' object.

Session Tracking :

Session tracking is a mechanism that is used to maintain state about a series of requests from the same user(that is, requests originating from the same browser) across some period of time. A session id is a unique token number assigned to a specific user for the duration of that user's session. Methods to work with session :

1. Cookies

2. URL Rewriting

3. Hidden Fields

4. Session API

EXAMPLE :

This example explains creating session and using session information with the help of session API. JSP provides an implicit object called session which can be used to work with session. You can set and get attributes to the session with the help of "setAttribute()" and "getAttribute()' methods respectively. Other session information (session id, session creation time, session last accessed time etc.) can also found using appropriate methods. We have created trackuserSession.jsp page which will help you to understand how to work with session.

trackuserSession.jsp

<%@page import = "java.util.*" session="true"%>

<HTML>

<HEAD>

<TITLE>Tracking user's session</TITLE>

</HEAD>

<BODY bgcolor="red">

<font size="+3" color="#E6E6E6"><br>Tracking user's session</font>

<TABLE style="background-color: silver;" border="1">

<%

Integer counter = (Integer)session.getAttribute("counter");

if (counter == null) {

counter = 1;

}

else {

counter = counter+1;

}

/* setAttribute() binds counter value to this session,

0

using the specified name here "counte".*/

session.setAttribute("counter", counter);

%>

1

<!-- use getId() method to get a unique session id -->

<tr><th>Session ID</th><td><%=session.getId()%></td></tr>

2

<!-- getCreationTime() method returns date and time

when session was created -->

3

<tr><th>Session creation time</th><td><%=new

Date(session.getCreationTime())%></td></tr>

4

<!--getlastAcccessTime() method returns date and time of

last access by this session id-->

<tr><th>Last accessed time</th><td><%=new

5

Date(session.getLastAccessedTime())%></td></tr>

<!-- this counter variable will print how much time user

6

visited in application -->

<tr><th>visited</th><td><%=counter%> times</td></tr>

</TABLE>

7

</BODY>

</HTML>

OUTPUT :

8

Download Source Code

Ads