Understanding HttpSession: Concepts, Methods, and Practical Examples
This article explains the fundamentals of HttpSession in Java web applications, covering its server‑side nature, underlying JSESSIONID cookie mechanism, lifecycle, common API methods, configuration, and provides several practical code examples such as login verification, shopping cart handling, duplicate‑submission prevention, and cookie‑disabled session strategies.
HttpSession is a server‑side technology used to maintain a session between a client and a web server, similar to cookies. It is obtained via request.getSession() (or its overloaded form with a boolean argument).
The underlying implementation relies on a special cookie named JSESSIONID. The cookie stores a unique session identifier generated by the server; the server uses this ID to locate the corresponding HttpSession object stored in memory.
When a session starts, the servlet container creates an HttpSession object, assigns it a unique Session ID, and sends that ID to the client as a cookie. On each subsequent request, the container reads the Session ID from the request, retrieves the matching HttpSession, and provides access to stored state such as a shopping cart.
Commonly used HttpSession methods include: public Object getAttribute(String name) – returns the object bound to the given name or null if none. public void setAttribute(String name, Object value) – binds an object to the session, replacing any existing binding with the same name. public void removeAttribute(String name) – removes the binding for the given name. public void invalidate() – invalidates the session and removes all bindings.
Session timeout can be configured in web.xml:
<session-config>
<session-timeout>1</session-timeout> <!-- minutes -->
</session-config>For serialization safety, all beans stored in the session should implement java.io.Serializable so that the server can persist them when the application is stopped.
Example 1 – One‑time login with verification code
request.getSession().setAttribute("code", sb.toString());
String code = request.getParameter("code");
String sessionCode = (String) request.getSession().getAttribute("code");
// compare code and sessionCode
response.setHeader("Refresh", "2;URL=/day08");
request.getSession().invalidate(); // destroy all session data
request.getSession().removeAttribute("user"); // destroy specific attributeExample 2 – Simple shopping cart
HttpSession session = request.getSession();
List<Book> cart = (List<Book>) session.getAttribute("cart");
if (cart == null) {
cart = new ArrayList<Book>();
session.setAttribute("cart", cart);
}
cart.add(book);
// later, display cart contents
HttpSession session = request.getSession(false);
if (session == null) {
out.write("Sorry, you have not shopped yet.");
} else {
List<Book> cart = (List<Book>) session.getAttribute("cart");
if (cart == null) {
out.write("Sorry, you have not shopped yet.");
} else {
out.write("Your purchased items:<br/>");
for (Book b : cart) {
out.write(b.getName() + "<br/>");
}
}
}Example 3 – Preventing duplicate form submission
Generate a token, store it in the session, and include it as a hidden field in the form:
<input type='hidden' name='token' value='"+token+"'/>Token creation:
String token = "" + System.currentTimeMillis() + new Random().nextLong();
token = MD5Util.md5(token);
request.getSession().setAttribute("token", token);
// alternatively, use UUID
String token = UUID.randomUUID().toString();Verification on submission:
String formToken = request.getParameter("token");
String sessionToken = (String) request.getSession().getAttribute("token");
if (formToken.equals(sessionToken)) {
// normal processing
System.out.println("Saved: " + name);
request.getSession().removeAttribute("token");
} else {
out.write("Please do not submit repeatedly");
}Form markup and JavaScript to disable the submit button after one click:
<form id='f1' action='RegistServlet' method='post'>
<input id='bt1' type='button' value='Register' onclick='toSubmit()'/>
</form>
<script type='text/javascript'>
function toSubmit() {
document.getElementById('f1').submit();
document.getElementById('bt1').disabled = true;
}
</script>When cookies are disabled, session data can still be preserved by URL rewriting using response.encodeURL(url), which appends JSESSIONID to the URL. Alternatively, inform users not to disable cookies.
END
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
IT Xianyu
We share common IT technologies (Java, Web, SQL, etc.) and practical applications of emerging software development techniques. New articles are posted daily. Follow IT Xianyu to stay ahead in tech. The IT Xianyu series is being regularly updated.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
