14 - JSP Session Tracking Techniques

14.1 Overview of JSP Session tracking

In a web application, server may be responding to several clients at a time so session tracking is a way by which a server can identify the client. As we know HTTP protocol is stateless which means client needs to open a separate connection every time it interacts with server and server treats each request as a new request.

Now to identify the client ,server needs to maintain the state and to do so , there are several session tracking techniques.

14.2 Session Tracking Techniques

There are four techniques which can be used to identify a user session.

a) Cookies

b) Hidden Fields

c) URL Rewriting

d) Session Object

With Cookies , Hidden Fields and URL rewriting approaches, client always sends a unique identifier with each request and server determines the user session based on that unique identifier where as session tracking approach using Session Object uses the other three techniques internally.

14.2.1 Cookie

Cookie is a key value pair of information, sent by the server to the browser and then browser sends back this identifier to the server with every request there on.

There are two types of cookies:

· Session cookies - are temporary cookies and are deleted as soon as user closes the browser. The next time user visits the same website, server will treat it as a new client as cookies are already deleted.

· Persistent cookies - remains on hard drive until we delete them or they expire.

If cookie is associated with the client request, server will associate it with corresponding user session otherwise will create a new unique cookie and send back with response.

We will discuss Cookie in detail in one of the upcoming chapters .

Cookie object can be created using a name value pair. For example we can create a cookie with name sessionId with a unique value for each client and then can add it in a resposne so that it will be sent to client:

Cookie cookie = new Cookie(“sessionID”, “some unique value”);

The major disadvantage of cookies is browser provides a way to disable the cookies and in that case server will not be able to identify the user.If our application uses cookies for session management and our users disable the cookie , then we will be in a big trouble.

14.2.2 Hidden Field

Hidden fields are similar to other input fields with the only difference is that these fields are not displayed on the page but its value is sent as other input fields. For example

      <input type=”hidden” name=”sessionId” value=”unique value”/>

is a hidden form field which will not displayed to the user but its value will be send to the server and can be retrieved using request.getParameter(“sessionId”) .

With this approach ,we have to have a logic to generate unique value and HTML does not allow us to pass a dynamic value which means we cannot use this approach for static pages. In short with this approach, HTML pages cannot participate in session tracking.

14.2.3 URL Rewriting

URL Rewriting is the approach in which a session (unique) identifier gets appended with each request URL so server can identify the user session. For example if we apply URL rewriting on http://localhost:8080/jsp-tutorial/home.jsp , it will become something like

?jSessionId=XYZ where jSessionId=XYZ is the attached session identifier and value XYZ will be used by server to identify the user session.

There are several advantages of URL rewriting over above discussed approaches like it is browser independent and even if user’s browser does not support cookie or in case user has disabled cookies, this approach will work.

Another advantage is , we need not to submit extra hidden parameter.

As other approaches, this approach also has some disadvantages like we need to regenerate every url to append session identifier and this need to keep track of this identifier until the conversation completes.

14.2.4 Session Object

Session object is representation of a user session. User Session starts when a user opens a browser and sends the first request to server. Session object is available in all the request (in entire user session) so attributes stored in Http session in will be available in any servlet or in a jsp.

When session is created, server generates a unique ID and attach that ID with the session. Server sends back this Id to the client and there on , browser sends back this ID with every request of that user to server with which server identifies the user

How to get a Session Object – By calling getSession() API on HttpServletRequest object (remember this is an implicit object)

a) HttpSession session = request.getSession()

b) HttpSession session = request.getSession(Boolean)

Destroy or Invalidate Session –

This is used to kill user session and specifically used when user logs off. To invalidate the session use -


Other important methods

· Object getAttribute(String attributeName) – this method is used to get the attribute stored in a session scope by attribute name. Remember the return type is Object.

· void setAttribute(String attributeName, Object value)- this method is used to store an attribute in session scope. This method takes two arguments- one is attribute name and another is value.

· void removeAttribute(String attributeName)- this method is used to remove the attribute from session.

· public boolean isNew()- This method returns true if server does not found any state of the client.

Browser session and server sessions are different. Browser session is client session which starts when you opens browser and destroy on closing of browser where as server session are maintained at server end.

Let’s discuss Session Tracking using Session Object with the help of examples.

14.3 JSP Session Tracking Examples

14.3.1 Printing session info

Write an example to print session Id , session creation time and last accessed time and a welcome message if client has visited again.

Solution- HttpSession API provides a method getId() which returns the associated session Id , getCreationTime() to get the session creation time and getLastAccessedTime() to get session last accessed time. Similarly isNew() method can be used to identify the new users

getLastAccessedTime() and getCreationTime() returns the time as long data type so to convert it to display format, create a date object passing long value in it.

a) Write sessionInformation.jsp with the below content in WebContent directory which will get the session object and displays its attributes

   <title> Display Session Information </title> 
  <%@page import="java.util.Date" %> 
       long creationTime = session.getCreationTime();     
       String sessionId = session.getId();     
       long lastAccessedTime = session.getLastAccessedTime();     
       Date createDate= new Date(creationTime);     
       Date lastAccessedDate= new Date(lastAccessedTime);     
       StringBuffer buffer = new StringBuffer();     
         buffer.append("<h3>Welcome </h3>");         
          buffer.append("<h3>Welcome Back!! </h3>");     
       buffer.append("<STRONG> Session ID : </STRONG>" + sessionId);     buffer.append(" <BR/> ");  
       buffer.append("<STRONG> Session Creation Time </STRONG>: " + createDate);     
       buffer.append(" <BR/> "); buffer.append("<STRONG> Last Accessed Time : </STRONG>" + lastAccessedDate);     
       buffer.append(" <BR/> ");        
    <%=         buffer.toString()     %>         



Hit the URL http://localhost:8080/jsp-tutorial/sessionInformation.jsp

and it will display session related information (refer below figure).

Hold on for a couple of seconds and refresh the page .This time you will see that session Id and session creation time will remain same but the last accessed time will be changed (highlighted below). Also you will see “Welcome Back” message instead “Welcome”

Last accessed time is the time when you accessed the session last and since we did wait for some time and accessed the session again, it is modified.

Now close the browser and again hit the same URL (http://localhost:8080/jsp-tutorial/sessionInformation.jsp) and see the difference. This time session Id is different which means new session is created because we closed the browser and opened a new one so server created a new session for the user. Since this is a new session , we can see Welcome message.


14.3.2 JSP session  invalidate

Explain session.invalidate() API with the help of example.

Solution- session.invalidate() invalidates the session or we can say it kills the corresponding server session. This API is most commonly used when a logged in user logs out. Once the session is invalidated, any other call on that server will throw an error.

a) create a login.jsp to grab username and password of user.

b) displayLoginDetails.jsp which will store the username in session and will create a link and clicking on that will invoke logout.jsp

c) logout.jsp will call session.invalidate() to kill the server session.

d) will try to access session object after invalidate which will throw an error.

Create login.jsp

<!DOCTYPE html> 
      <title>Login Form</title> 
     <form name="logonform" action="displayLoginDetails.jsp" method="POST"> 
       Username: <input type="text" name="username"/> <br/> 
       Password:<input type="password" name="password"/> <br/> 
       <input type="submit" value="Submit"/> 

Create displayLoginDetails.jsp

    <title>Display Details</title> 
    <%  String username=request.getParameter("username");   
      String password=request.getParameter("password");     
      String message="Username is : "+ username + "
      Password is :" + password ;     
      message = message + "<br/>To logout click on Logout Link <br/>" ;    
      message = message + "<a href=\"logout.jsp\"> Logout</a>";  
    <strong>     <%= message %>     </strong> 

Create logout.jsp

    <title>logout </title> 
     // try to access session object      


Access login.jsp using the url http://localhost:8080/jsp-tutorial/login.jsp

and enter any username and password

On submit it you will see below figure

Clicking Logout link will logout.jsp which will invalidate the session and then tries to access the username from session. Accessing session after it has been invalidated will throw the exception (refer below figure)


14.4 Browser Session vs. Server Session

By default session tracking is based on cookie (session cookie) which is stored in browser memory and not on hard drive. So as soon as browser is closed, that cookie is gone and will not b retrieved again.

Corresponding to this session identifier, a server session is created at server and will be available until it is invalidated or maximum inactive time has been reached. When user closes the browser without logging off, server does not know that browser has been closed and thus server session remains active till configured maximum inactive time has been reached.

Maximum inactive session time ( in minutes) can be configured in web.xml like below

      <session-config>     <session-timeout>15</session-timeout> </session-config> 

14.5 Store Attributes in Session object wisely

At a first glance it looks very convenient to store attributes in session as it is available on any JSP or servlet within the same session. You have to be very careful while storing attributes in session as it can be modified by another JSP or servlet accidently which will result in undesirable behaviour.

Confused? Okay lets think of a situation where your application has two jsp. One JSP (FetchBalance) calls some database system and pulls out bank account balance and stores in a session variable (“accountBalance”) for later use.

You have another JSP “UpdateBalance” which updates the database with the value of “accountBalance” session variable.

There is another developer who is also working on your web application and does not know that you have created a session variable “accountBalance” so he also thought of creating a session variable with same name and stores it value as 0.

Now in any flow if prior the execution of UpdateBalance, if JSP written by second developer gets executed then it will change the session variable “accountBalance” value ot 0 and then UpdateBalance will update the account balance in database to 0

So Long Story short “Use Session Variables Wisely”.

Like us on Facebook