Java.Servlet.What are cookies?

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:

  1. Server sends a cookie using the Set-Cookie header.
  2. Browser stores the cookie locally (temporary or persistent).
  3. 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 CaseExample
Session trackingKeeping users logged in
PersonalizationRemembering user preferences (theme, language)
AnalyticsTracking user visits
Shopping cartsRemembering 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:

PropertyDescription
NameKey (must be unique per domain+path)
ValueAssociated data (can be string, needs encoding if special characters)
DomainWhich domain the cookie belongs to
PathWhich path the cookie applies to (e.g., /shop)
Max-AgeLifetime in seconds (0 = delete immediately, no set = session cookie)
SecureOnly send cookie over HTTPS
HttpOnlyCan’t be accessed by JavaScript (for security)
SameSiteControls cross-site behavior (Lax, Strict, None)

🧩 Types of Cookies:

TypeMeaning
Session CookiesTemporary, deleted when browser closes (no Max-Age set)
Persistent CookiesStored until expiration date (Max-Age or Expires set)
Secure CookiesSent only over HTTPS
HttpOnly CookiesNot 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.
” 🎯

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