Tuesday, 3 June 2014

Servlets : Cookie Create/Delete/Get

🚀 Master Java & Servlets with Ram N Java!

Subscribe to get clear, beginner-friendly tutorials right when they drop.

🔔 Subscribe to Ram N Java

Working with Cookies in Java Servlets

Cookies are small textual key-value pairs created on the server and stored on the client browser. They are one of the most widely used mechanisms for session tracking, storing user preferences, and remembering login details across requests.

The Java Servlet API makes it simple to manage cookie lifecycles using the jakarta.servlet.http.Cookie (or javax.servlet.http.Cookie) class.

1. How to Create and Send a Cookie

To create a cookie and attach it to the HTTP response, instantiate a Cookie object with a key and value, optionally set its max age, and add it using HttpServletResponse:

Cookie userCookie = new Cookie("username", "JohnDoe");
userCookie.setMaxAge(60 * 60 * 24); // Persistent for 24 hours (in seconds)
response.addCookie(userCookie);

2. How to Retrieve Cookies from a Request

When a browser makes a request, it sends back stored cookies in the request header. You can read them by calling getCookies() on HttpServletRequest:

Cookie[] cookies = request.getCookies();
if (cookies != null) {
  for (Cookie c : cookies) {
    if ("username".equals(c.getName())) {
      String value = c.getValue();
    }
  }
}

3. How to Delete a Cookie

The Servlet API does not provide a direct deleteCookie() method. To delete an existing cookie from the client's browser, you overwrite it by setting its maximum age to zero (0) and sending it back:

Cookie deleteCookie = new Cookie("username", "");
deleteCookie.setMaxAge(0); // Deletes immediately
response.addCookie(deleteCookie);

Recommended Next Watch

Master session management and cookie handling in Servlets with these tutorials:

No comments:

Post a Comment

Tutorials