Skip to content

Session management

Session management in servlets helps maintain a connection between a user and your web server. It's like a digital handshake that says, "Hey, you're still here, let me remember what you were up to!" This handshake allows your website to remember important information about each user, like their preferences, shopping cart items, or login status, even as they click from one page to another.

Session tracking types

  1. Cookies: Think of cookies as the digital equivalent of leaving a little trail of breadcrumbs. When a user visits your website for the first time, a small piece of data, known as a cookie, is stored on their device. This cookie contains information about the session, such as a unique identifier. Every time the user interacts with your website thereafter, their browser sends this cookie back to the server, allowing it to recognize and track the user's session.

  2. URL Rewriting: Imagine giving each guest a special map with their name on it as they enter your event. With URL rewriting, we add unique session identifiers directly into the URLs of our web pages. So, as users navigate through different pages on our website, their session information travels along with them in the URL. It's like a personalized guide leading them through the digital landscape of our site.

  3. Hidden Form Fields: Picture providing each guest with a secret code that they whisper to gain access to different parts of your event. In servlets, we can embed hidden form fields within web forms. These fields contain session information that gets passed back to the server when the form is submitted. It's a subtle yet effective way to maintain session continuity without cluttering the user interface.

  4. Session Tracking API: Now, imagine having a dedicated team of event planners who oversee every guest's journey throughout your event. In servlets, we have the Session Tracking API, which provides a more comprehensive and centralized approach to managing sessions. With this API, we can create, retrieve, and manage session objects directly within our servlet code, giving us full control over the session lifecycle.

Imagine you're running a bakery website where customers can order delicious treats online. You want to provide a personalized experience by remembering their favorite items, even if they leave the website and come back later. This is where cookies in servlets come into play.

Suppose a customer named Sarah visits your bakery website for the first time. As soon as she arrives, your servlet generates a unique cookie and sends it to her browser. This cookie contains information like Sarah's session ID and her preferences, such as her favorite pastry – let's say it's chocolate chip cookies.

Now, whenever Sarah clicks around your website, her browser automatically includes this cookie in the request headers. So, when she adds chocolate chip cookies to her cart, the servlet receives her request along with the session ID stored in the cookie. The servlet then knows it's Sarah and can update her shopping cart accordingly.

Here's how we can implement cookies in a servlet:

java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LanguagePreferenceServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // Get the user's preferred language from the request
        String language = request.getParameter("language");

        // Create a new cookie to store the language preference
        Cookie languageCookie = new Cookie("languagePreference", language);

        // Set the cookie's expiration time (in seconds)
        languageCookie.setMaxAge(365 * 24 * 60 * 60); // 1 year

        // Add the cookie to the response
        response.addCookie(languageCookie);

        // Set response content type
        response.setContentType("text/html");

        // Display a confirmation message to the user
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h2>Language Preference Set!</h2>");
        out.println("<p>Your preferred language has been set to: " + language + "</p>");
        out.println("</body></html>");
    }
}

In this example, we've created a servlet called LanguagePreferenceServlet that handles GET requests. When a user submits a form with their preferred language choice, this servlet is invoked. We retrieve the selected language from the request parameters and create a new cookie named "languagePreference" to store this information.

Next, we set the cookie's expiration time to one year using setMaxAge(), ensuring that the language preference persists across multiple sessions. Then, we add the cookie to the response using response.addCookie().

Finally, we send a response back to the user's browser, confirming that their language preference has been successfully set.

Session tracking api or HttpSession

Imagine you're developing a web application where users can create and manage their tasks. The Session Tracking API can help us maintain user sessions and store task-related data securely on the server-side.

Here's how we can implement the Session Tracking API in a servlet:

java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class TaskManagerServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // Set response content type
        response.setContentType("text/html");

        // Retrieve the current session, or create a new one if none exists
        HttpSession session = request.getSession(true);

        // Retrieve the user's task list from the session, or create a new one if none exists
        TaskList taskList = (TaskList) session.getAttribute("taskList");
        if (taskList == null) {
            taskList = new TaskList();
            session.setAttribute("taskList", taskList);
        }

        // Retrieve task information from the request parameters
        String taskName = request.getParameter("taskName");

        // If a task name is provided, add it to the user's task list
        if (taskName != null && !taskName.isEmpty()) {
            taskList.addTask(taskName);
        }

        // Display the user's task list
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h2>Task Manager</h2>");
        out.println("<form action='addTask' method='post'>");
        out.println("Task Name: <input type='text' name='taskName'><br>");
        out.println("<input type='submit' value='Add Task'>");
        out.println("</form>");
        out.println("<h3>Task List:</h3>");
        out.println("<ul>");
        for (String task : taskList.getTasks()) {
            out.println("<li>" + task + "</li>");
        }
        out.println("</ul>");
        out.println("</body></html>");
    }
}

In this example, we've created a servlet called TaskManagerServlet that handles GET requests. When a user accesses the task manager page, this servlet is invoked. We retrieve the current session using request.getSession(true), ensuring that a new session is created if none exists.

Next, we retrieve the user's task list from the session. If the task list doesn't exist yet, we create a new TaskList object and store it in the session. Then, we retrieve the task name from the request parameters.

If a task name is provided, we add it to the user's task list. We then generate the HTML response for the task manager page, allowing users to add tasks and view their task list.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.