Session Management in Java Servlets
HTTP is stateless, but web applications need to remember users across requests. HttpSession provides server-side storage keyed by a session ID sent to the browser as a cookie.
How HttpSession Works
When you call request.getSession(true), the container creates a session (if none exists) and sends a JSESSIONID cookie to the browser. On subsequent requests, the browser sends this cookie back, allowing the server to retrieve the same session and its stored attributes.
Common Session Operations
HttpSession session = request.getSession();
session.setAttribute("user", loggedInUser);
User user = (User) session.getAttribute("user");
session.invalidate(); // Logout — destroys session
int timeout = session.getMaxInactiveInterval(); // secondsSession Timeout
Sessions expire after a period of inactivity (default 30 minutes in Tomcat). Configure in web.xml with <session-timeout>20</session-timeout> (minutes) or programmatically with session.setMaxInactiveInterval(1200). Always invalidate sessions on logout.
Security Best Practices
- Store minimal data in sessions—prefer user ID over full user objects.
- Regenerate session ID after login to prevent session fixation attacks.
- Use HTTPS in production to protect JSESSIONID from interception.
- Never store passwords or sensitive tokens in session attributes.
- Set appropriate timeout values for banking vs. content sites.
Frequently Asked Questions
Session vs Cookie — what's the difference?▼
Sessions store data on the server; only a session ID cookie is sent to the browser. Cookies store data directly on the client. Sessions are more secure for sensitive data but consume server memory.
