Java Notes
Complete guide to session management in Java Servlets - HttpSession, URL rewriting, hidden form fields, session attributes, and session timeout configuration.
Why Session Tracking?
HTTP is a stateless protocol — each request is independent, and the server doesn't remember previous requests from the same client. Session tracking mechanisms allow the server to identify and maintain state across multiple requests from the same user.
Use Cases:
- User login status
- Shopping cart contents
- User preferences
- Multi-page form data
- Page visit tracking
HttpSession — The Primary Approach
Creating and Getting Sessions
@WebServlet("/session-demo")
public class SessionDemoServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get existing session or create new one
HttpSession session = request.getSession(); // creates if not exists
// HttpSession session = request.getSession(true); // same as above
// HttpSession session = request.getSession(false); // returns null if no session
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h2>Session Information</h2>");
out.println("<p>Session ID: " + session.getId() + "</p>");
out.println("<p>Created: " + new java.util.Date(session.getCreationTime()) + "</p>");
out.println("<p>Last Accessed: " + new java.util.Date(session.getLastAccessedTime()) + "</p>");
out.println("<p>Is New: " + session.isNew() + "</p>");
out.println("<p>Max Inactive Interval: " + session.getMaxInactiveInterval() + "s</p>");
}
}Storing and Retrieving Session Attributes
Invalidating Sessions (Logout)
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session != null) {
// Remove specific attributes
session.removeAttribute("username");
session.removeAttribute("role");
// Or invalidate entire session (recommended for logout)
session.invalidate();
}
// Clear session cookie from browser
Cookie sessionCookie = new Cookie("JSESSIONID", "");
sessionCookie.setMaxAge(0);
sessionCookie.setPath("/");
response.addCookie(sessionCookie);
response.sendRedirect("/login");
}
}Shopping Cart Example
@WebServlet("/cart/*")
public class ShoppingCartServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
List<String> cart = (List<String>) session.getAttribute("cart");
if (cart == null) {
cart = new ArrayList<>();
session.setAttribute("cart", cart);
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h2>Shopping Cart (" + cart.size() + " items)</h2>");
out.println("<ul>");
for (String item : cart) {
out.println("<li>" + item + "</li>");
}
out.println("</ul>");
out.println("<p>Total items: " + cart.size() + "</p>");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
List<String> cart = (List<String>) session.getAttribute("cart");
if (cart == null) {
cart = new ArrayList<>();
session.setAttribute("cart", cart);
}
String action = request.getParameter("action");
String item = request.getParameter("item");
if ("add".equals(action) && item != null) {
cart.add(item);
} else if ("remove".equals(action) && item != null) {
cart.remove(item);
} else if ("clear".equals(action)) {
cart.clear();
}
response.sendRedirect("/cart");
}
}URL Rewriting
When cookies are disabled, the session ID is appended to URLs:
@WebServlet("/url-rewrite-demo")
public class URLRewriteServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
Integer count = (Integer) session.getAttribute("visitCount");
count = (count == null) ? 1 : count + 1;
session.setAttribute("visitCount", count);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// URL rewriting — encodes session ID in URL
String encodedURL = response.encodeURL("/url-rewrite-demo");
String encodedRedirectURL = response.encodeRedirectURL("/dashboard");
out.println("<h2>Visit Count: " + count + "</h2>");
out.println("<a href=\"" + encodedURL + "\">Visit Again</a><br>");
out.println("<a href=\"" + encodedRedirectURL + "\">Go to Dashboard</a>");
// Output URL looks like: /url-rewrite-demo;jsessionid=ABC123XYZ
}
}Hidden Form Fields
@WebServlet("/register-step2")
public class RegisterStep2Servlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Pass data from step 1 as hidden fields
out.println("<form action=\"/register-complete\" method=\"POST\">");
out.println("<input type=\"hidden\" name=\"name\" value=\"" + name + "\">");
out.println("<input type=\"hidden\" name=\"email\" value=\"" + email + "\">");
out.println("<input type=\"text\" name=\"phone\" placeholder=\"Phone\">");
out.println("<input type=\"text\" name=\"address\" placeholder=\"Address\">");
out.println("<button type=\"submit\">Complete Registration</button>");
out.println("</form>");
}
}Session Configuration in web.xml
Session Listeners
@WebListener
public class SessionListener implements HttpSessionListener, HttpSessionAttributeListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("Session created: " + se.getSession().getId());
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("Session destroyed: " + se.getSession().getId());
}
@Override
public void attributeAdded(HttpSessionBindingEvent event) {
System.out.println("Attribute added: " + event.getName() + " = " + event.getValue());
}
@Override
public void attributeRemoved(HttpSessionBindingEvent event) {
System.out.println("Attribute removed: " + event.getName());
}
@Override
public void attributeReplaced(HttpSessionBindingEvent event) {
System.out.println("Attribute replaced: " + event.getName());
}
}HttpSession Methods Reference
| Method | Description |
|---|---|
getId() | Returns session ID |
getAttribute(name) | Get stored attribute |
setAttribute(name, value) | Store attribute |
removeAttribute(name) | Remove attribute |
getAttributeNames() | All attribute names |
invalidate() | Destroy session |
isNew() | True if session just created |
getCreationTime() | When session was created |
getLastAccessedTime() | Last request time |
setMaxInactiveInterval(sec) | Set timeout |
getMaxInactiveInterval() | Get timeout |
Common Mistakes
- Not checking for null session —
getSession(false)can return null - Storing large objects in session — Consumes server memory
- Not invalidating on logout — Session remains accessible
- Using sessions for all data — Use request attributes for page-level data
- Not handling session timeout — Users see errors instead of login redirect
Interview Key Points
- HTTP is stateless; sessions add state across requests
- HttpSession stores data on the server (JSESSIONID cookie tracks client)
getSession()creates session;getSession(false)returns null if none- Session timeout: configurable via code or web.xml
invalidate()destroys the session completely- URL rewriting is fallback when cookies are disabled
- Sessions consume server memory — store only essential data
Summary
In this chapter, we learned about Session Tracking in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Session Tracking.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, servlets, jsp, session
Related Java Master Course Topics