Java.Servlet.Can i delete Cookie ?

✅ To delete a cookie:

  1. Create a new cookie with the same name as the one you want to delete.
  2. Set its Max-Age to 0.
  3. (Optional but important) Set the same path as the original cookie (otherwise it might not match).

Finally, add it to the response.

🎯 Example: Deleting a Cookie

Cookie cookie = new Cookie("userName", "");  // Name must match
cookie.setMaxAge(0);                         // 0 means delete immediately
cookie.setPath("/");                         // Must match original path
response.addCookie(cookie);                  // Add it back to instruct browser

✅ What happens:

  • When the browser receives a cookie with Max-Age=0, it removes the cookie immediately.

⚡ Important Things to Remember:

PointWhy
Cookie name must match exactlyOtherwise the browser doesn’t know which cookie to remove
Cookie path must matchIf path differs, it won’t recognize the cookie to delete
Domain (if set originally) must matchOtherwise browser might keep old cookie
Always addCookie() even for deletionDeleting is just sending a “zero-age” cookie back

🚀 Practical Full Example

✅ Suppose you earlier created:

Cookie cookie = new Cookie("userName", "Alice");
cookie.setMaxAge(3600);
cookie.setPath("/");
response.addCookie(cookie);

✅ Now to delete it later:

Cookie deleteCookie = new Cookie("userName", "");
deleteCookie.setMaxAge(0);
deleteCookie.setPath("/");
response.addCookie(deleteCookie);

🔥 Real Life Scenario

  • After a user logs out, you usually delete session-related cookies like “userId” or “JSESSIONID” (if not managed automatically).
  • Important for security and privacy.

🛠️ Quick Summary:

Can I delete a cookie?✅ Yes
How?Set Max-Age = 0 and addCookie()
Should name and path match original?✅ Yes, absolutely
Browser behaviorBrowser removes the cookie immediately

⚡ Final Memory Trick:

To delete a cookie: same name + same path + Max-Age 0 + send it back.” 🎯

This entry was posted in Без рубрики. Bookmark the permalink.