Servlets · Lesson 6
Cookies in Servlets
What Cookies Do
A cookie is a small name-value pair that a browser sends back to a server on matching requests. Servlets use cookies for preferences, correlation identifiers, and limited client-side state. Cookies are not a replacement for secure server-side session storage.
Creating and Reading a Cookie
The Cookie API lets a servlet set attributes such as its path, lifetime, and security flags. Always treat a cookie value as untrusted input because the client can change it.
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 ThemeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
Cookie themeCookie = new Cookie("theme", "dark");
themeCookie.setMaxAge(60 * 60 * 24 * 30);
themeCookie.setPath(request.getContextPath());
themeCookie.setHttpOnly(true);
themeCookie.setSecure(request.isSecure());
response.addCookie(themeCookie);
response.setContentType("text/plain;charset=UTF-8");
response.getWriter().println("Theme preference saved");
}
}
Cookie Attributes
| Attribute | Effect | Typical reason |
|---|---|---|
Max-Age | Controls lifetime | Persistent preference |
Path | Limits request paths | Scope a cookie to an application |
HttpOnly | Blocks most script access | Reduce cookie theft through scripts |
Secure | Sends only over HTTPS | Protect transport |
SameSite | Limits cross-site sending | Reduce CSRF exposure |
Common Mistake and Practices
Common Mistake: Putting passwords, authorization decisions, or unencrypted personal data directly in a cookie. Clients can inspect and modify cookie values, even when the cookie is marked
HttpOnly.
- Use
HttpOnlyandSecurewhere appropriate. - Keep cookie values short and non-sensitive.
- Set an explicit path and lifetime.
- Validate values before using them.
- Prefer a server-side session for confidential state.
Real-World Use Case
A learning platform stores a non-sensitive theme preference in a cookie so the interface can restore dark or light mode on a later visit. The account and progress data remain on the server behind the authenticated session.
Quiz Check