How do I handle cookies using Jakarta Servlet API?

Handling cookies in the Jakarta Servlet API is simple and straightforward. Cookies are small bits of data sent from a server to a client and then sent back by the client in subsequent requests to the server. Below is how you can handle cookies using Jakarta Servlet API:

1. Creating and Adding a Cookie

To create a cookie, use the jakarta.servlet.http.Cookie class. You can add the cookie to the response using the HttpServletResponse object.

Example: Adding a Cookie

package org.kodejava.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/addCookie")
public class AddCookieServlet extends HttpServlet {
   @Override
   protected void doGet(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
      // Create a new cookie
      Cookie cookie = new Cookie("username", "john_doe");

      // Set cookie properties
      cookie.setMaxAge(24 * 60 * 60); // 1 day (in seconds)
      cookie.setHttpOnly(true);      // Makes it inaccessible to JavaScript
      cookie.setSecure(true);        // Send it only over HTTPS

      // Add the cookie to the response
      response.addCookie(cookie);

      response.getWriter().println("Cookie has been set!");
   }
}

2. Reading Cookies

To read cookies, use the HttpServletRequest object to retrieve all cookies with the getCookies() method, and then search for the desired cookie.

Example: Retrieving a Cookie

package org.kodejava.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/readCookie")
public class ReadCookieServlet extends HttpServlet {
   @Override
   protected void doGet(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
      Cookie[] cookies = request.getCookies();

      if (cookies != null) {
         for (Cookie cookie : cookies) {
            if ("username".equals(cookie.getName())) {
               response.getWriter().println("Found cookie: "
                                            + cookie.getName() + " = "
                                            + cookie.getValue());
               return;
            }
         }
      }

      response.getWriter().println("Cookie not found!");
   }
}

3. Deleting a Cookie

To delete a cookie, set its maximum age to 0 and add it back to the response. When the browser sees the cookie with a 0 age, it will remove it.

Example: Deleting a Cookie

package org.kodejava.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

public class DeleteCookieServlet extends HttpServlet {
   @Override
   protected void doGet(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
      Cookie[] cookies = request.getCookies();

      if (cookies != null) {
         for (Cookie cookie : cookies) {
            if ("username".equals(cookie.getName())) {
               Cookie deleteCookie = new Cookie("username", "");
               deleteCookie.setMaxAge(0);  // Mark cookie for deletion
               response.addCookie(deleteCookie);
               response.getWriter().println("Cookie has been deleted!");
               return;
            }
         }
      }

      response.getWriter().println("Cookie not found!");
   }
}

Important Notes

  1. Secure Cookies: Always mark cookies as secure (cookie.setSecure(true)) if you’re using HTTPS, to prevent transmission over unsecured connections.
  2. HttpOnly Flag: Use cookie.setHttpOnly(true) to prevent cookies from being accessed via client-side scripts, enhancing security.
  3. Path and Domain Settings: Cookies can be restricted to certain paths or domains to control their scope:
    cookie.setPath("/secure");
    cookie.setDomain(".example.com");
    
  4. Cookie Expiration:
    • cookie.setMaxAge(x): Sets the lifespan in seconds. x = 0 deletes the cookie, and x = -1 makes it a session cookie (deleted when the browser is closed).

Maven dependencies

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.1.0</version>
    <scope>provided</scope>
</dependency>

Maven Central

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.