What are Java server sessions?

Server session

A server session refers to the state of communication established between a web server and a client, typically a web browser. Server sessions enable storing and retrieving user-specific data, allowing web applications to maintain state across multiple requests. Each session is assigned a unique identifier—session ID—to associate session data with a specific client. Since HTTP protocol is stateless, we require server sessions to maintain a stateful communication between a HTTP client and a server.

Java server session

We need to use Java servlets to implement the functionality of server sessions in the Java programming language. Servlets are Java programs that run on a web server to process client requests and send back a server response.

Workflow of Java server session

  1. When a client initiates a session by visiting a website, the server generates a unique session ID using the setAttribute method and sends it to the client.

  2. The server then stores the client-specific data and session ID.

  3. The client includes the assigned session ID in each of the subsequent requests to the server.

  4. The server then passes the session ID as an argument to the getAttribute method to retrieve and send the session-specific data to the client.

Server session workflow
Server session workflow

Implementation in Java

Here is an interactive example that demonstrates user authentication. Follow the steps below to run the web application:

  1. Click the “Run” button.

  2. Wait 2 seconds for the application to load, then click the link below the “Run” button.

  3. On the top of the web page, we add /hello/login.html to the end of the URL.

  4. After submitting the login details, the server stores the login information securely which can then be viewed by viewing the profile.

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        // Get the session object associated with the request
        HttpSession session = request.getSession();

        // Set session attributes
        session.setAttribute("username", "user123");
        session.setAttribute("isLoggedIn", true);

        // Retrieve session attributes
        String username = (String) session.getAttribute("username");
        boolean isLoggedIn = (Boolean) session.getAttribute("isLoggedIn");

        // Remove session attribute
        session.removeAttribute("isLoggedIn");

        // Invalidate the session
        session.invalidate();

        // Redirect the user to another page
        response.sendRedirect("home.jsp");

    }
}
Implementation of java server session

Code explanation

In the above example, we have a servlet named SessionServlet to demonstrate server sessions in Java.

  • Line 10: The doGet method of SessionServlet is invoked when the servlet receives a request from the client.

  • Line 13: To access the HttpSession object associated with the client’s request, we use the getSession method.

  • Line 16–17: The setAttribute method creates session attributes that store session-specific information about the client.

  • Line 20–21: Once created, session attributes can be accessed using the getAttribute method.

  • Line 24: When the client logs out of the web application, we can remove the isLoggedIn attribute by invoking the removeAttribute method.

  • Line 27: When the client closes the web browser, the session is terminated using the invalidate method.

  • Line 30: Finally, if the client is authenticated, it is redirected to the homepage of the web application.

Applications

  1. User authentication

    • Sessions can store the login information to authorize users.
  2. Shopping carts

    • E-commerce applications store shopping cart data across multiple pages.
  3. Personalization

    • By storing their preferences and language specifics, users actively receive a personalized website experience.

Best Practices

  1. Session security: The proper handling of session IDs, encryption, and secure transmission is essential to protect against session hijacking and other security threats.

  2. Session expiration: Configuring session timeouts helps preserve server resources and user sessions effectively.

Conclusion

Java server sessions are a fundamental way to manage stateful client-server interactions across the web. When the best practices are encouraged and thoroughly adopted, sessions empower web applications to deliver personalized user experiences and maintain continuity throughout multiple requests.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved