Sobes.tech
Middle

What session management methods do you know in servlets?

sobes.tech AI

Answer from AI

  • Use of Cookies
  • Use of hidden form fields (URL Rewriting)
  • Use of the HttpSession interface

HttpSession is the most common and recommended method. When a client first accesses the application, the server creates an HttpSession object, generates a unique session identifier (JSESSIONID), and sends it back to the client. The client stores the identifier (usually in a cookie) and sends it with each subsequent request. The server finds the corresponding HttpSession object based on this identifier.

Example of using HttpSession:

// Get the current session or create a new one if it does not exist
HttpSession session = request.getSession();

// Set an attribute in the session
session.setAttribute("userName", "Alice");

// Get an attribute from the session
String userName = (String) session.getAttribute("userName");

// Set session timeout to 30 minutes (in seconds)
session.setMaxInactiveInterval(30 * 60);

// Invalidate the session
session.invalidate();

Cookie: The server can send a cookie to the client containing session information. The client sends these cookies back with each request.

Cookie sessionCookie = new Cookie("sessionInfo", "someValue");
response.addCookie(sessionCookie);

URL Rewriting: Adds the session identifier to the URL of each request as a parameter. Used when the client does not support cookies.

String encodedURL = response.encodeURL("/myapp/page?productId=123");
What session management methods do you know in… - sobes.tech