Sessions and Cookies
Sessions and Cookies
HTTP is stateless - each request is independent. Sessions and cookies let you remember users across requests. A cookie is a small value stored on the client. A session is a server-side store tied to a client.
Cookies
Cookies are sent from the server to the client via the Set-Cookie header. The browser sends them back with every subsequent request to that domain.
// Setting a cookie
Cookie cookie = new Cookie("theme", "dark");
cookie.setMaxAge(7 * 24 * 60 * 60); // 7 days
cookie.setPath("/");
resp.addCookie(cookie);
// Reading cookies
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (Cookie c : cookies) {
if ("theme".equals(c.getName())) {
String theme = c.getValue();
}
}
}
HttpSession
The servlet container provides sessions automatically. Each session has a unique ID stored in a cookie called JSESSIONID. The container maps this ID to an HttpSession object on the server.
// Starting a session (or getting existing one)
HttpSession session = req.getSession();
// Storing data
session.setAttribute("user", currentUser);
session.setAttribute("cart", shoppingCart);
// Reading data
User user = (User) session.getAttribute("user");
// Removing data
session.removeAttribute("cart");
// Invalidating the entire session
session.invalidate();
Session Timeout
Sessions expire after a period of inactivity. Configure it in web.xml or via code:
<session-config>
<session-timeout>30</session-timeout>
</session-config>
Or in code: session.setMaxInactiveInterval(1800); (30 minutes in seconds).
Session vs Cookie
Use cookies for small, non-sensitive preferences (theme, language). Use sessions for authentication state, shopping carts, and any data that should not be tampered with by the client.
Key Points
- Cookies are client-side storage; sessions are server-side storage.
- The
JSESSIONIDcookie links the browser to its server-side session. - Use
getSession()to create or retrieve a session. - Sessions expire after a configurable timeout period.
- Use cookies for preferences, sessions for authentication and sensitive data.