Using Cookies for Session Management
One of the common uses of cookies in web applications is to manage user sessions, which are temporary interactions between the client and the server. A session can store user-specific information, such as the login status, the shopping cart items, or the preferences. To use cookies for session management in Servlets, you need to use the HttpSession interface from the javax.servlet.http package. You can get an HttpSession object from the request object by using the getSession method, which creates a new session if one does not exist, or returns the existing one if it does. The getSession method also creates a cookie named JSESSIONID with a unique identifier for the session and adds it to the response object. You can use the setAttribute, getAttribute, and removeAttribute methods of the HttpSession object to store, retrieve, and delete session data. For example, the following code creates a session and stores the user name and role in it:
HttpSession session = request.getSession(); // get or create session<br>
session.setAttribute("name", "John"); // store name in session<br>
session.setAttribute("role", "admin"); // store role in session
The following code retrieves the session data and prints it to the console:
HttpSession session = request.getSession(false); // get existing session or null<br>
if (session != null) {<br>
String name = (String) session.getAttribute("name"); // get name from session<br>
String role = (String) session.getAttribute("role"); // get role from session<br>
System.out.println("Name: " + name + ", Role: " + role);<br>
}
The following code deletes the session data and invalidates the session:
HttpSession session = request.getSession(false); // get existing session or null<br>
if (session != null) {<br>
session.removeAttribute("name"); // delete name from session<br>
session.removeAttribute("role"); // delete role from session<br>
session.invalidate(); // invalidate session<br>
}
The invalidate method also removes the JSESSIONID cookie from the client's browser.