Cookies in Java Servlets
Cookies are small pieces of data stored in the user's browser and sent with every request to your domain. Servlets use them for preferences, tracking, and remember-me functionality.
Creating Cookies
Cookie cookie = new Cookie("language", "en-AU");
cookie.setMaxAge(60 * 60 * 24 * 365); // 1 year
cookie.setHttpOnly(true);
cookie.setSecure(true); // HTTPS only
cookie.setPath("/");
response.addCookie(cookie);Reading Cookies
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie c : cookies) {
if ("language".equals(c.getName())) {
String lang = c.getValue();
}
}
}Deleting Cookies
To delete a cookie, create a Cookie with the same name and path, set maxAge to 0, and add it to the response. The browser will remove it on the next request.
Cookie Security
- HttpOnly — Prevents JavaScript access (mitigates XSS).
- Secure — Cookie only sent over HTTPS.
- SameSite — Controls cross-site cookie sending (CSRF protection).
- Never store passwords or JWTs in cookies without encryption.
Frequently Asked Questions
How many cookies can I set?▼
Browsers typically allow 50 cookies per domain with a 4KB size limit per cookie. Keep cookie payloads small.
