Category: java
Session management cookies httpsession
Published on 30 Sep 2026
Explanation
HTTP is stateless, so session management is required when an application needs to remember information about a user across multiple requests.
Code:
Request 1 β Login Request 2 β Dashboard Request 3 β Profile Session keeps user information available across requests.
Explanation
A cookie is a small piece of data stored by the browser and sent back to the server with subsequent requests.
Code:
Cookie cookie = new Cookie("username", "Praveen");
response.addCookie(cookie);
Explanation
Read cookies from an incoming request using getCookies().
Code:
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
System.out.println(cookie.getName());
}
}
Explanation
HttpSession stores server-side information associated with a particular user session.
Code:
HttpSession session = request.getSession();
session.setAttribute("username", "Praveen");
Explanation
Retrieve and remove session attributes using getAttribute() and removeAttribute().
Code:
String username =
(String) session.getAttribute("username");
session.removeAttribute("username");