Open In App

Session Management in Java

Last Updated : 09 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Session is used to save user information momentarily on the server. It starts from the instance the user logs into the application and remains till the user logs out of the application or shuts down the machine. In both cases, the session values are deleted automatically. Hence, it functions as a temporary storage that can be accessed till the user is active in the application and can be accessed when the user requests a URI. This session is stored in binary values, hence maintaining the security aspect, and can be decoded only at the server end.

What is Session Management?

Keeping track of the user’s preferences over a website or an application as long as the user is logged into the system for a specific time is called Session Management. This lasts until they log out or their session expires. In simpler terms, it’s like keeping a record of user activities when they simply surf the application so that from next time onwards, the user doesn’t have to specify the preferences again.

Why is it Required?

Sessions are required because they perform multiple functions ranging from time management to security perspective. The following can be noted in this regard.

  • Sessions store the user authentication credentials in an encrypted format which can be passed in case of auto login.
  • Since the values are encrypted, it can store sensitive information as well.
  • Session values can be accessed in a short period cause they are stored on the client’s end and thus it helps the server to respond faster.
  • It can restrict application access from multiple servers, thus securing the network.

Role of Cookies and Other Tracking Mechanisms

Cookies and other tracking mechanisms play a crucial role in session management by helping applications remember the users through multiple interactions and their preferences and behavior. Below are some of the mechanisms through which they manage the task.

1. Session Cookies

  • Identification: When the user logs into the system, an ID is generated. This is a unique identifier that is stored in the session cookie assigned to an individual user which identifies the user on their forthcoming visits.
  • Temporary Storage: The details stored in temporary in nature, such as login status and other session-specific data.
  • Automatic Logins: They store the user’s authentication credentials which helps the user to not provide the credentials every a time they are logging into the system. It performs as an auto login where it will take the details from the session cookie and login to the platform. This can be performed with some time frame to identify the user or in simpler words, this can be stored for a specific time period to maintain security of the system.

2. Persistent Cookies

  • Extended Recognition: Unlike session cookies which expires when the user closes browser, persistent cookies generally have a longer lifespan.
  • Personalization: Persistent cookies can store user preferences providing a personalized experience across multiple visits of the user to the platform.

3. Tracking Mechanisms

  • User Activity Tracking: Websites may use JavaScript or pixels as tracking mechanisms to monitor the user’s activity enhancing user experience and analytics.
  • Third-Party Cookies: For this very purpose, some websites prefer third-party cookies which are generally set by domains.

4. Security Measures

  • CSRF Tokens: Cookies can also store anti-CSRF (Cross-Site Request Forgery) tokens to prevent unauthorized actions, thus enhancing the overall security of the platform.
  • Secure and HttpOnly Flags: Cookies can also be marked with HttpOnly flag to prevent client-side scripts from accessing them which convey as secure to ensure they are only transmitted over secure (HTTPS) connections, thus reducing the risk of certain types of attacks.

How to Get a Session?

We can keep track of a client’s session with the HttpSession object. In Java Servlets, the HttpSession interface provides a way to regulate the state/information about a user varying across multiple requests. It is a part of javax.servlet.http package and allows storing and retrieving the attributes about the user’s information, providing a mechanism for session management.

Retrieving HttpSession in Servlets

We can use the getSession() method to create a HttpSession object. The getSession() method returns a session if it already exists or creates a new one, in case no session exists. The following snippet follows.

HttpSession session = request.getSession();

Using the parameterized getSession(boolean) method, it returns a new session if we pass the true parameter. The syntax will look something like this.

HttpSession session = request.getSession(true);

Further, to fetch a pre-existing session, one can pass false in the parameterized getSession() method.

HttpSession session = request.getSession(false);

Common Methods

1. setAttribute(String name, Object value)

This associates the specified value to the specified name in a particular session. This can be used to store data that needs to be managed across multiple requests.

HttpSession session = request.getSession();
session.setAttribute("username", "GFG");

2. getAttribute(String name)

Returns the value which is associated with the specified name in the particular session. This is used to retrieve previously stored session attributes.

HttpSession session = request.getSession();
String username = (String) session.getAttribute("username");

3. removeAttribute(String name)

It removes the attribute with the specified name from the session.

HttpSession session = request.getSession();
session.removeAttribute("username");

4. invalidate()

Once the services are completed, it is necessary to destroy the session object. The syntax follows.

HttpSession session = request.getSession();
session.invalidate();

Example

Java




import javax.servlet.http.*;
  
@WebServlet("/api")
public class GFG extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        // Retrieve the HttpSession object
        HttpSession session = request.getSession();
  
        // Use HttpSession methods
        session.setAttribute("username", "GFG");
        String value = (String) session.getAttribute("username");
    }
}


In the above example, the getSession() method is called on the HttpServletRequest object to retrieve the HttpSession. Once you have the HttpSession object, you can use its methods to set and retrieve session attributes.

Session Tracking Mechanisms in Servlets

To maintain the session between a web server and a web client, following methods can be used.

1. Cookies

To address the client subsequent request, the web server assigns a unique session ID as a cookie to the web client so that for the next oncoming requests, this cookie can be passed and the server can identify its validity and can process the request.

This is not considered an efficient approach as it is browser dependent and some browser at times doesn’t support a cookie. The general syntax follows.

Cookie cookie = new Cookie("sessionId", "123456");
response.addCookie(cookie);

2. Hidden Form Fields

A web server can also pass a hidden HTML form field as an input element along with a unique session ID as follows.

<input type = "hidden" name = "sessionId" value = "12345">

This simply adds the name and value on each and every request which the client sends to the server and the response is received, the session_id value can be used to track different browser actions.

Since clicking on a regular ankle tag (<a href=””>) hypertext link doesn’t results into form submission, so this can’s support general session tracking and so can’t be an efficient way to handle the transmission of information.

3. URL Rewriting

Simply appending the URL with some data or token as the session id which can be decoded at the server end, which can associate that data with its stored session values and can identify the legitimate request can be done by URL rewriting.

This appending can be done in the form of passing query parameters with a sessionid value. This can be accessed at the server side to identify the client request.

Though this can help to maintain the information flow between the server and the client and would be independent of the browser, but this is generated dynamically. Thus, this will not be considered a choice for static pages.

String urlWithSessionId = response.encodeURL("/api");

Session Lifecycle

The stages which a user session goes through right from its creation to its eventual expiration completes the session lifecycle. In the context of web applications, the lifecycle involves the management of user-specific data across multiple session requests. The key stages involved in the session lifecycle are described below.

1. Session Creation

  • Trigger: The session is created when the user logs into the application for the initial time.
  • Action: The servlet container creates a new session for the user using HttpSession attribute when the user logs in the platform for the first time. As no existing session is associated with the user, it creates a new one and generates a session ID which is stored as a cookie on the client’s browser based on the system requirements.

2. Attribute Setting

  • Trigger: Once the session is created, the required attributes are set on the session using the servlets or the JSP page.
  • Action: The required attribute are named and stored using the setAttribute method of the HttpSession object which makes sure that this can be use across multiple locations.
HttpSession session = request.getSession();
session.setAttribute("username", "GFG");

3. Client Interaction

  • Trigger: The user interacts with the web application, making additional requests.
  • Action: The session ID is now associated with each successive request, allowing the servlet container to map the request with the correct session. To retrieve the attributes associated to the particular session, use getAttribute method.
HttpSession session = request.getSession();
String username = (String) session.getAttribute("username");

4. Session Invalidation

  • Trigger: The session can be invalidated explicitly by the application or automatically based on certain criteria as per the system requirements.
  • Action: We can invoke invalidate method to remove all the session attributes associated with that particular session. Further we can use a timeout concept which will invalidate the sessions automatically after a specified period of inactivity.
HttpSession session = request.getSession();
session.invalidate();

5. Session Expiration

  • Trigger: We can set the session timeout, which is a defined maximum time of existence.
  • Action: Once the browsing is completed, we can remove the data and the user’s preference based on the maximum inactive time interval.
HttpSession session = request.getSession();
// Session will be invalidated after 30 minutes of inactivity
session.setMaxInactiveInterval(1800);

Example of Session Management

Below example demonstrates creating a session, setting and retrieving attributes, and finally, invalidating the session.

Java




import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
  
@WebServlet("/api")
public class GFG extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Get the HttpSession object. If it doesn't exist, a new one will be created.
        HttpSession session = request.getSession();
  
        // Set a session attribute
        session.setAttribute("username", "GFG");
  
        // Retrieve the session attribute
        String username = (String) session.getAttribute("username");
  
        // Display the attribute value in the response
        response.getWriter().println("Username from Session: " + username);
          
        // Invalidate the session after displaying the attribute
        session.invalidate();
    }
}


Explaination of the above Example:

  • A servlet named /api is created.
  • When a user accesses the servlet, the doGet method is called which retrieves the existing HttpSession associated with the request or creates a new one if it doesn’t exist using the request.getSession() method.
  • The servlet sets a session attribute named “username” to the value “GFG” using session.setAttribute.
  • It retrieves the “username” attribute from the session using session.getAttribute and prints it in the HTTP response.
  • Finally, the session.invalidate() method is called to invalidate the session.

Conclusion

The concept of session management becomes crucial when dealing with dynamic and large web applications. A session provides the details about the user’s interactions with a site which can be managed using HttpSession interface in Java Servlets.

Some of the session tracking mechanisms include cookies, URL rewriting and hidden form fields which are used to maintain continuity across multiple user requests. The HttpSession interface allows for the setting and retrieval of attributes in the particular session, making it possible to store user-related information. The lifecycle involves stages such as attribute setting, client interaction, session invalidation, and expiration, right from the creation till its expiration or invalidation ensuring the proper management of user sessions and thus securing the user’s personal data.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads