✅ Session Management means tracking user interactions across multiple HTTP requests.
Because:
- HTTP is stateless by design.
- Every HTTP request is independent — the server forgets everything about the previous request.
- So if you want a user to “stay logged in”, “keep items in cart”, “remember settings” — you must explicitly manage session state!
🎯 Different Methods of Session Management in Servlets
Method | How it works | Description |
---|---|---|
Cookies | Store a session ID in a small text file in the browser | Most common default way |
URL Rewriting | Add session ID as part of URL query string | Backup if cookies are disabled |
Hidden Form Fields | Pass session ID manually in hidden <input> fields | Only works for form submissions |
HttpSession API | Java object automatically tied to session ID | Easiest and most robust way in Servlets |
🚀 Now, Let’s Understand Each One Carefully:
✅ 1. Cookies
- Server sends a Set-Cookie header with a session ID.
- Browser stores it and automatically sends it back with each request.
✅ Server-side in servlet:
HttpSession session = request.getSession();
session.setAttribute("username", "Alice");
Browser sees:
Set-Cookie: JSESSIONID=ABC123DEF456
Next request will automatically include:
Cookie: JSESSIONID=ABC123DEF456
⚡ If cookies are disabled, this method won’t work unless you fallback to URL rewriting.
✅ 2. URL Rewriting
- When cookies are disabled, server can append session ID to URLs.
Example:
https://example.com/profile;JSESSIONID=ABC123DEF456
✅ In Java, you use:
String encodedURL = response.encodeURL("profile.jsp");
encodeURL()
will automatically append session ID only if needed (if cookies are not working).
⚡ Drawbacks:
- Session ID is visible in URL (security risk if copied/shared).
✅ 3. Hidden Form Fields
- Pass session ID manually inside a form as a hidden input field.
Example:
<form action="checkout" method="POST">
<input type="hidden" name="sessionId" value="ABC123DEF456">
<input type="submit" value="Checkout">
</form>
✅ Server reads:
String sessionId = request.getParameter("sessionId");
⚡ Problems:
- Only works if user submits forms (not for normal URL clicks).
- Manual management needed — annoying and risky.
✅ 4. HttpSession API (Servlet Built-in)
- Servlet containers (like Tomcat) handle all session tracking for you automatically.
- You work with
HttpSession
object.
✅ Example:
HttpSession session = request.getSession();
session.setAttribute("username", "Alice");
String username = (String) session.getAttribute("username");
✅ Features:
- Timeout configuration.
- Session invalidation (
session.invalidate()
). - Attribute management (store any Java objects).
✅ Best practice: always prefer HttpSession API unless you have very special needs.