✅ “Session” in web development means:
A way to remember a user’s data between different HTTP requests.
Because HTTP is stateless by design:
- Every request is independent.
- The server doesn’t remember if two requests come from the same user.
So a session is like giving the user an invisible ID badge, so the server can recognize them across multiple requests.
✅ Example:
- You log into a website → the server creates a session for you.
- The server stores your info in memory: cssCopyEdit
Session ID: X123ABC
Data: { username: "Stanley", role: "admin" }
- The server gives you a session ID (either as a cookie or inside a URL).
- Every next request you make includes your session ID, and the server finds your session in memory.
Result: You stay logged in, your cart stays full, etc.
✅ In Java Servlets:
- Session is represented by
HttpSession
object. - You can get the session like this:
HttpSession session = request.getSession();
session.setAttribute("username", "Stanley");
Now “Stanley” is stored in the server’s memory under your session ID.
Later, you can retrieve it:
String username = (String) session.getAttribute("username");
✅ Where the Session ID is stored?
- Normally in a cookie (
JSESSIONID
). - If cookies are disabled, it can be passed in the URL (
;jsessionid=...
).
✅ Session Lifetime:
- Sessions live for a time (like 30 minutes of inactivity).
- After that, they expire (the server deletes them).
- You can also manually destroy a session:
session.invalidate();
✅ Real life analogy:
Imagine visiting a hotel:
- You check in at the lobby → they give you a room keycard (= session ID).
- Every time you enter your room, you use the keycard → hotel knows it’s you.
- If you lose the keycard, you can’t get back in (session lost).
✨ Quick Visual:
Request # | Without session | With session |
---|---|---|
1 | Hello, who are you? | Hello, welcome back Stanley! |
2 | Hello, who are you? | Hello again Stanley! |
3 | Hello, who are you? | Hello again Stanley! |
Summary:
- A session allows the server to remember a user across multiple requests.
- It stores small data (like login info, shopping carts, etc.) server-side.
- It uses session IDs to connect requests to the correct user.