The HttpSession interface in Java Servlets enables servers to maintain user-specific state across multiple HTTP requests. When a client makes its first request, the server creates a session and assigns it a unique identifier (JSESSIONID). This ID is sent to the client as a cookie. Subsequent requests from the client include this cookie, allowing the server to retrieve the corresponding session object and access stored data.
Key characteristics of HttpSession:
- Data is stored on the server side.
- Supports storage of any Java object type.
- Uses a key-value map where values are of type
Object. - No inherent size limit for stored data.
A session is obtained via HttpServletRequest.getSession(). If no session exists (i.e., no JSESSIONID is present in the request), a new one is created. The overloaded method getSession(boolean create) allows control over session creation: if false, it returns null when no session exists instead of creating one.
Common session operations include:
session.setAttribute("userRole", "admin");
String role = (String) session.getAttribute("userRole");
Enumeration<String> keys = session.getAttributeNames();
session.removeAttribute("userRole");
String sessionId = session.getId();
Sessions can be terminated in two ways:
- Timeout: Configured in
web.xmlusing<session-timeout>(in minutes). The timer resets with each request. Example:
<session-config>
<session-timeout>5</session-timeout>
</session-config>
This setting applies per web application. A global timeout can be set in Tomcat’s conf/web.xml, but application-specific settings override it.
- Explicit invalidation: Calling
session.invalidate()immediately destroys the session and unbinds all attributes.
The session lifecycle begins up on the first call to getSession() or getSession(true). It ends either when invalidated programmatically or after exceeding the configured inactive period. By default, Tomcat sets a 30-minute timeout.
Compared to cookies:
- Storage location: Cookies reside on the client; sessions on the server.
- Security: Session are more secure since sensitive data isn’t exposed to the client.
- Capacity: Cookies are limited (~4KB per cookie, ~20 per domain); sessions have no practical limits.
Best practices suggest storing only essential, non-critical data like authentication tokens or user roles—not full business objects—due to session lifetime unpredictability.
Example: Storing session data
@WebServlet("/init-session")
public class SessionInitServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
HttpSession session = req.getSession();
session.setAttribute("userId", "U1001");
session.setAttribute("accessLevel", "premium");
}
}
Example: Retrieving session data
@WebServlet("/use-session")
public class SessionUseServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
HttpSession session = req.getSession(false);
if (session != null) {
String id = (String) session.getAttribute("userId");
String level = (String) session.getAttribute("accessLevel");
System.out.println("User: " + id + ", Level: " + level);
System.out.println("Created: " + session.getCreationTime());
System.out.println("Last accessed: " + session.getLastAccessedTime());
System.out.println("Timeout (sec): " + session.getMaxInactiveInterval());
}
}
}