🧠 In Servlets, you work with cookies using the javax.servlet.http.Cookie class.
Here’s the full list of the main methods for working with cookies:
🎯 Methods of the Cookie Class
| Method | Purpose | Example |
|---|---|---|
getName() | Get the cookie name | cookie.getName() |
getValue() | Get the cookie value | cookie.getValue() |
setValue(String value) | Set/change the cookie value | cookie.setValue("newValue") |
getDomain() | Get the domain for the cookie | cookie.getDomain() |
setDomain(String pattern) | Set the domain (e.g., .example.com) | cookie.setDomain(".example.com") |
getPath() | Get the path for which the cookie is valid | cookie.getPath() |
setPath(String uri) | Set the path (e.g., /shop) | cookie.setPath("/shop") |
getMaxAge() | Get the lifetime of the cookie in seconds | cookie.getMaxAge() |
setMaxAge(int expiry) | Set how long the cookie should live (in seconds) | cookie.setMaxAge(3600) |
getSecure() | Check if cookie is sent only over HTTPS | cookie.getSecure() |
setSecure(boolean flag) | Force cookie to be sent only over HTTPS | cookie.setSecure(true) |
isHttpOnly() | Check if cookie is HttpOnly | cookie.isHttpOnly() |
setHttpOnly(boolean isHttpOnly) | Set cookie as HttpOnly (inaccessible to JS) | cookie.setHttpOnly(true) |
toString() | Get cookie info as a String | cookie.toString() |
🛠️ Other Important Servlet Methods for Working with Cookies
✅ From HttpServletResponse:
(Used for sending cookies to the client)
| Method | Purpose |
|---|---|
addCookie(Cookie cookie) | Add a cookie to the response |
✅ From HttpServletRequest:
(Used for reading cookies sent by the client)
| Method | Purpose |
|---|---|
getCookies() | Returns an array of Cookie objects from the request |
🚀 Full Mini Example:
✅ Setting a cookie:
Cookie cookie = new Cookie("userName", "Alice");
cookie.setMaxAge(60 * 60); // 1 hour
cookie.setPath("/"); // Make cookie available for entire app
cookie.setSecure(true); // Send only over HTTPS
cookie.setHttpOnly(true); // Prevent JavaScript access
response.addCookie(cookie);
✅ Reading cookies:
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("userName".equals(cookie.getName())) {
String value = cookie.getValue();
// Use value
}
}
}
✅ Deleting a cookie:
Cookie cookie = new Cookie("userName", "");
cookie.setMaxAge(0); // 0 means delete immediately
cookie.setPath("/");
response.addCookie(cookie);
⚡ Quick Practical Tips:
| Tip | Why |
|---|---|
Always set a path (setPath("/")) | Otherwise, cookie might not be visible to all your pages |
Use setHttpOnly(true) for sensitive cookies | Improves security (prevent XSS attacks) |
Use setSecure(true) if your app uses HTTPS | Prevents cookie leakage over HTTP |
| Remember cookies are small! | Browsers limit cookie size (~4KB) and number of cookies |
🔥 Quick Memory Trick:
“Cookies in servlets = Create (addCookie), Read (getCookies), Delete (setMaxAge(0)).” 🎯