Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Session Tracking
2.1.
Session Management
2.2.
Need of Session Tracking
3.
Techniques for Session Tracking
3.1.
Cookies
3.1.1.
Methods in Cookie Object
3.2.
Hidden Variables
3.3.
URL Rewriting
3.4.
Session Object
3.4.1.
How to Get a Session Object 
3.4.2.
Methods in Session Object
4.
Session Tracking Example
5.
Frequently Asked Questions
6.
Key Takeaways
Last Updated: Mar 27, 2024

Session Tracking

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

A session is time duration. It starts from the client’s conversation with the server and terminates at the end of it. The data we transfer from the client to the server through multiple requests during a particular session is known as the session’s state.

It is important to manage the client’s previous request when processing a request in web applications. A container prepares a request object when the request is received from the client, and it destroys the request object when the response is dispatched to the client. 

Hence, it is not sufficient to manage the client’s previous requests. To represent a particular user, a separate session is prepared. To keep track of all the session’s objects at the server, we need to set an explicit mechanism known as Session Tracking Mechanism.

Session Tracking

Sometimes we need to transfer the data between multiple forms in our applications. However, in the form-based applications, we use HTTP protocol which is a stateless protocol that means it remembers only the current conversation. E.g., if we leave the first form and enter into the second form, we will forget about the previous form data.

To overcome this limitation and to transfer the data between multiple forms, we refer to the following methodologies:

  1. Cookies
  2. Hidden Variables
  3. URL Rewriting
  4. Session Object

 

These techniques allow clients to send a unique identifier with each request, which enables the server to determine the user session based on these unique identifiers.

Session Management

 

Source: Link

 

Session Management is used to recognize a particular user. It is a way to maintain the user’s state about a series of requests from the same user (from the same browser) across the same period. Each time the user requests the server, the server treats the request as a new one.

Need of Session Tracking

When a client makes a request, a new connection is established to the webserver for each request. It becomes difficult for servers to identify whether the requests are coming from the same user or not. Also, the server does not keep track of the information of the previous request made by the user.

To overcome this problem, we need to maintain a unique id for every request that helps to maintain a complete conversation between the client and the server.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Techniques for Session Tracking

Source: Link

Cookies

Cookies are used to transfer the data between multiple form-based applications. A cookie is a tiny piece of information sent by the server to the client—every cookie stores the data in the form of a key-value pair. The server adds the cookie to the response header by using the Set-Cookie header and sends the cookie to the client. Cookies are stored in the browser by using the website’s domain name. A browser can contain cookies from multiple domains. The client needs to use the HeaderCookie to get all the cookies available in the browser.

There are two types of cookies:

  • Session cookies - These cookies are temporary and are deleted as soon as the user closes the browser, after which, if the user visits the same website, the server treats it as a new client.
     
  • Persistent cookies - These cookies remain on the hard drive until the user deletes them or expires.

 

Syntax: 

Cookie myCookie = new Cookie(“SessionID”, “SessionValue”)

 

Creating a Cookie:

Cookie cookie=new Cookie("client","Coding Ninjas");  //creating cookie object  
response.addCookie(cookie);  //adding cookie in the response  

 

Source: Link

 

Methods in Cookie Object

  1. getComment (): This returns a comment describing the purpose of the cookie.
  2. getMaxAge (): This returns the maximum specified age of the cookie.
  3. getName() : This returns the name of the cookie.
  4. getPath() : This returns the URL for which cookie is targeted.
  5. getValue() : This returns the value of the cookie.
  6. setComment(String): This comment is used to describe the cookie’s purpose.
  7. setMaxAge(int): This is used to set the maximum age of the cookie. A zero value will cause a cookie to be deleted.
  8. setPath(String): It determines the cookie should begin with this URL.
  9. setValue(String): It is used to set the value of the cookie. Values with special characters should be avoided.

 

Advantages of cookies

  1. Cookies are better to transfer the data as once the cookie is stored, the data can be accessed directly on any page of the website.

 

Disadvantages of cookies

  1. If the client disables the cookies in the browser, the server will not identify the user.
  2. Cookies are not recommended for security reasons.
  3. It becomes complicated when a huge amount of data between the server and the client is required to share

 

Hidden Variables

We have to use the hidden fields given by HTML to use variables. These hidden fields must be specified as a part of the <form> and with the name and value attributes. These fields are not displayed to the client, but their value is sent as other input fields. When the form has been submitted, the name and the value fields are automatically included in the GET and the POST data. The value in the above example can be retrieved using a request.getParameter(“xxx”)

 

Syntax:

<input type=”hidden” name=”xxx” value=”CN”/>

Here, the name is the hidden field, and CN represents the hidden field value.

 

Advantages of hidden variables

  1. The hidden variables consume less memory.
  2. Once the browser is closed, the data of hidden variables clear automatically.

 

Disadvantages of hidden variables

  1. It is complicated to carry a huge amount of data using hidden variables.
  2. Hidden variables are not recommended to transfer sensitive data.
  3. This approach cannot be used for static pages.

 

URL Rewriting

URL Rewriting is an approach in which a session ID gets appended with each request URL so the server can identify the user session. 

Consider the following example:

http://localhost:8080/jsp/index.jsp?sessionid=” ABC”

 

By using a unique identifier, the server can easily identify the user. It is known as handling the browsers. When the user clicks on the new rewritten link, the servlet easily recognizes the SessionID.

 

Advantages of URL rewriting

  1. There is no need to pass hidden values.
  2. This method works even if the user has disabled cookies.
  3. This technique is independent of the browser.

 

Disadvantages of URL rewriting

  1. The client needs to append the sessionID and regenerate the URL with each request.
  2. Also, the client needs to keep track of the unique ID until the conversation ends between the client and the server.

 

Session Object

The session object is a representation of a user session. User Session starts when a user opens the web browser and sends the first request to the server. The session object is available in the entire user session, so the attributes stored in the HTTP session will be available in a servlet or a JSP.

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

To handle the session object explicitly, we have to write the following page re-directive in the JSP code:

<%@ page session=”false|true”%>

 

Advantages of Session object

  1. The Session Object technique is more reliable as each user has its uniqueID, which is helpful to access the data stored at the server-side.

 

How to Get a Session Object 

Calling the getSession() method on HttpServletRequest object.

a) HttpSession session = request.getSession()

b) HttpSession session = request.getSession(Boolean)

session.invalidate(): This method kills a user session and is used specifically when the user logs off.

 

Methods in Session Object

  • public Object getAttribute(String attributeName): This method is used to get the attribute stored in the session scope by an attribute name. The return type of this method is an Object.
     
  • public Enumeration getAttributeNames(): These methods return an enumeration of string objects containing the names of all the objects bound to that session.
     
  • public long getCreationTime(): This method returned when the session was created.
     
  • public string getId(): This method returns a string containing the identifier assigned to this session.
     
  • public long getLastAccessedTime(): This method returns the last time the client sent a request associated with this session.
     
  • public int getMaxInvalidateInterval(): This method returns the max time interval when the container keeps the session open.
     
  • public int setMaxInactiveInterval(): This method returns the time before the container will invalidate the session.
     
  • public void setAttribute(String attributeName, Object value): This method stores an attribute in the session scope. 
     
  • public void removeAttribute(String attributeName): This method removes an attribute from a session.
     
  • public boolean isNew()- This method returns true if the server does not find any state of the client.

 

You can also read about the JSP Architecture and Lifecycle.

Session Tracking Example

Given an example, we will try to use the invalidate method in the session.

session. invalidate() kills the corresponding server session. This API is used when a logged-in user logs out. Once the session is invalidated, a call on that server will throw an error.

  • Create a login.JSP page to take the username and password of the user.
  • Displaydetails.JSP will store the username in session and create a link, which will invoke the logout.JSP page.
  • The logout.JSP will call the session. invalidate() to kill the server session.
  • Accessing the session object after invalidating will throw an error.

 

Login.jsp

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

 

Output:

Displaydetails.jsp

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

 

Output:

Logout.jsp

<html> 
  <head> 
    <title>Logout </title> 
  </head> 
  <body>     
    <%     
      session.invalidate();     
     // try to access session object      
     session.getAttribute("username");     
    %>     
  </body> 
</html>

 

Output:

 

Frequently Asked Questions

Q1. Why can’t we use the ServletContext object to manage the client’s previous request?

Ans: The ServletContext object shares its data to all the components used in the current application and to all the application users. Due to this, the ServletContext object cannot provide a clear-cut separation between the multiple users. 

 

Q2. How Browser session is different from Server Session?

Ans: To understand the difference between the Browser Session and the Server Session. Consider the following table:

 

Q3. Can we stop multiple submits to a web page that is initiated by clicking to refresh button?

Ans: Yes, it can be solved using a Post/Get/Redirect pattern.

  • A form gets submitted to the server using the POST or GET method.
  • The state in the database model is updated.
  • A redirect response is used to reply by the engine for a view page.
  • The browser loaded a view using the GET command, and no user’s data was sent.
  • This is safe from multiple submits as it is a separate JSP page.

 

Key Takeaways

This blog discussed session tracking and different techniques used in session tracking, with a few examples.

  • The data we transfer from the client to the server through multiple requests during a particular session is known as the session’s state.
  • The data we transfer from the client to the server through multiple requests during a particular session is known as the session’s state.
  • Session Management is used to recognize a particular user. It is a way to maintain the user’s state about a series of requests from the same user (from the same browser) across the same period.
  • Each time the user requests the server, the server treats the request as a new one.

 

If you are a beginner and interested in exploring other fields such as web development, core subjects, or competitive programming. In that case, you can follow our guided path to get a good grip on your concepts.

Previous article
JSP Form processing
Next article
JSP- File Uploading
Live masterclass