✅ Cookies are small pieces of data (key-value pairs) that a server sends to the client’s browser,
and the browser stores them and automatically sends them back to the server with each future request to the same server.
Think of cookies as the server leaving a note inside your browser:
→ “Hey, remember this next time!”
🎯 How Cookies Work Step-by-Step:
- Server sends a cookie using the
Set-Cookie
header. - Browser stores the cookie locally (temporary or persistent).
- For every future request to that server, the browser attaches the cookie using a
Cookie
header.
✅ Example:
- Server sends:
Set-Cookie: userId=12345; Max-Age=3600; Path=/
Browser stores it.
Next request automatically adds:
Cookie: userId=12345
Server can now recognize the user!
🚀 Why are Cookies Useful?
Use Case | Example |
---|---|
Session tracking | Keeping users logged in |
Personalization | Remembering user preferences (theme, language) |
Analytics | Tracking user visits |
Shopping carts | Remembering items added to cart |
🛠️ Cookies in Servlets
✅ To create a cookie:
Cookie cookie = new Cookie("username", "Alice");
cookie.setMaxAge(3600); // 1 hour
response.addCookie(cookie);
✅ To read cookies:
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("username".equals(cookie.getName())) {
String value = cookie.getValue();
// Use value
}
}
}
⚡ Important Properties of Cookies:
Property | Description |
---|---|
Name | Key (must be unique per domain+path) |
Value | Associated data (can be string, needs encoding if special characters) |
Domain | Which domain the cookie belongs to |
Path | Which path the cookie applies to (e.g., /shop ) |
Max-Age | Lifetime in seconds (0 = delete immediately, no set = session cookie) |
Secure | Only send cookie over HTTPS |
HttpOnly | Can’t be accessed by JavaScript (for security) |
SameSite | Controls cross-site behavior (Lax, Strict, None) |
🧩 Types of Cookies:
Type | Meaning |
---|---|
Session Cookies | Temporary, deleted when browser closes (no Max-Age set) |
Persistent Cookies | Stored until expiration date (Max-Age or Expires set) |
Secure Cookies | Sent only over HTTPS |
HttpOnly Cookies | Not accessible by client-side scripts (prevents XSS attacks) |
🛡️ Quick Example: Secure Login Session
✅ Server after login success:
Cookie sessionCookie = new Cookie("JSESSIONID", "ABC123XYZ");
sessionCookie.setHttpOnly(true);
sessionCookie.setSecure(true);
sessionCookie.setMaxAge(30 * 60); // 30 minutes
response.addCookie(sessionCookie);
🔥 Quick Practical Tip:
✅ Use cookies for small, essential data only.
❌ Don’t store sensitive information directly in cookies (like passwords!) — always store tokens, IDs, or references.
✅ Use HttpOnly and Secure flags whenever dealing with authentication cookies!
⚡ Quick Memory Trick:
“Cookies are your browser’s little notes from the server —
small, helpful, and sometimes a little too revealing.” 🎯