Servlet Session Management HttpSession, Cookies, URL Rewriting is an important Servlet topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.
For this page, focus on what problem Servlet Session Management HttpSession, Cookies, URL Rewriting solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: under 650 content words; limited checklist/practice/mistake/FAQ notes .
A strong understanding of Servlet Session Management HttpSession, Cookies, URL Rewriting should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.
Servlet Session Management HttpSession Cookies URL Rewriting should be studied as a practical Servlet lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.
In the servlet > session-management page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.
HTTP is stateless, so web applications need mechanisms to track users across requests. Servlets support four techniques:
| Technique | Storage | Pros | Cons |
|---|---|---|---|
| HttpSession | Server-side | Secure, large data | Server memory usage |
| Cookies | Client-side | Persistent, no server memory | Size limit (4KB), security risks |
| URL Rewriting | URL parameter | Works without cookies | Ugly URLs, security risk |
| Hidden Fields | HTML form | Simple | Only works with forms |
@WebServlet("/session-demo")
public class SessionServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String username = req.getParameter("username");
// Get or create session
HttpSession session = req.getSession(true);
// Store data
session.setAttribute("username", username);
session.setAttribute("loginTime", new java.util.Date());
session.setAttribute("role", "user");
// Configure session
session.setMaxInactiveInterval(30 * 60); // 30 minutes timeout
// Session info
String sessionId = session.getId();
boolean isNew = session.isNew();
long creationTime = session.getCreationTime();
long lastAccess = session.getLastAccessedTime();
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
out.println("<p>Session ID: " + sessionId + "</p>");
out.println("<p>Is New: " + isNew + "</p>");
out.println("<p>Username: " + session.getAttribute("username") + "</p>");
}
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// Logout: invalidate session
HttpSession session = req.getSession(false);
if (session != null) {
session.invalidate();
}
resp.sendRedirect(req.getContextPath() + "/login");
}
}
@WebServlet("/cookie-demo")
public class CookieServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// ===== Create Cookie =====
Cookie userCookie = new Cookie("username", "Alice");
userCookie.setMaxAge(7 * 24 * 60 * 60); // 7 days
userCookie.setPath("/");
userCookie.setHttpOnly(true); // Prevent XSS
userCookie.setSecure(true); // HTTPS only
resp.addCookie(userCookie);
// ===== Read Cookies =====
Cookie[] cookies = req.getCookies();
String username = null;
if (cookies != null) {
for (Cookie c : cookies) {
if ("username".equals(c.getName())) {
username = c.getValue();
break;
}
}
}
// ===== Delete Cookie =====
Cookie deleteCookie = new Cookie("username", "");
deleteCookie.setMaxAge(0); // Expire immediately
deleteCookie.setPath("/");
// resp.addCookie(deleteCookie); // Uncomment to delete
// ===== URL Rewriting (fallback when cookies disabled) =====
String encodedUrl = resp.encodeURL(req.getContextPath() + "/profile");
// Appends ;jsessionid=... if cookies are disabled
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
out.println("<p>Username from cookie: " + username + "</p>");
out.println("<a href='" + encodedUrl + "'>My Profile</a>");
}
}
When studying Servlet Session Management HttpSession, Cookies, URL Rewriting, separate three things: the concept, the syntax, and the situation where it is useful. This prevents the lesson from becoming a list of commands with no practical meaning.
In Servlet, Servlet Session Management HttpSession, Cookies, URL Rewriting becomes easier when you build a tiny example first, then increase complexity. Add one realistic input, one invalid or boundary input, and one explanation of why the result changes.
class ServletSessionManagementHttpSessionCookiesURLRewritingReview {
public static void main(String[] args) {
String state = "ready";
System.out.println("Servlet Session Management HttpSession Cookies URL Rewriting: " + state);
}
}
String value = null;
if (value == null) {
System.out.println("Servlet Session Management HttpSession Cookies URL Rewriting: handle the missing value before continuing");
}
Memorizing Servlet Session Management HttpSession Cookies URL Rewriting without the situation where it is useful.
Connect Servlet Session Management HttpSession Cookies URL Rewriting to a concrete Servlet task.
Testing Servlet Session Management HttpSession Cookies URL Rewriting only with the perfect input.
Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Changing code before reading the visible symptom or error message.
Inspect the output, state, configuration, or stack trace connected to Servlet Session Management HttpSession Cookies URL Rewriting.
Memorizing Servlet Session Management HttpSession Cookies URL Rewriting without the situation where it is useful.
Connect Servlet Session Management HttpSession Cookies URL Rewriting to a concrete Servlet task.
The common mistake is memorizing syntax without understanding when the behavior changes or fails.
Remember the problem it solves in Servlet, then attach the syntax or steps to that problem.
You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.
They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.
Explore 500+ free tutorials across 20+ languages and frameworks.