Java Notes
Complete guide to handling cookies in Java Servlets - creating, reading, modifying, deleting cookies, cookie attributes, and security best practices.
What are Cookies?
Cookies are small pieces of data (key-value pairs) stored on the client's browser and sent back to the server with every subsequent request. They provide a way to maintain state in the stateless HTTP protocol.
Creating and Sending Cookies
@WebServlet("/set-cookie")
public class SetCookieServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String theme = request.getParameter("theme");
// Create cookies
Cookie userCookie = new Cookie("username", username);
Cookie themeCookie = new Cookie("theme", theme);
Cookie visitCookie = new Cookie("lastVisit", String.valueOf(System.currentTimeMillis()));
// Set cookie properties
userCookie.setMaxAge(60 * 60 * 24 * 7); // 7 days
userCookie.setPath("/"); // Available to entire app
userCookie.setHttpOnly(true); // Not accessible via JavaScript
userCookie.setSecure(true); // Only sent over HTTPS
themeCookie.setMaxAge(60 * 60 * 24 * 30); // 30 days
themeCookie.setPath("/");
visitCookie.setMaxAge(60 * 60 * 24 * 365); // 1 year
visitCookie.setPath("/");
// Add cookies to response
response.addCookie(userCookie);
response.addCookie(themeCookie);
response.addCookie(visitCookie);
response.setContentType("text/html");
response.getWriter().println("<h2>Cookies Set Successfully!</h2>");
response.getWriter().println("<p>Username: " + username + "</p>");
response.getWriter().println("<a href=\"/read-cookie\">Read Cookies</a>");
}
}Reading Cookies
Modifying Cookies
@WebServlet("/update-cookie")
public class UpdateCookieServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// To modify a cookie, create a new one with same name
String newTheme = request.getParameter("theme");
Cookie themeCookie = new Cookie("theme", newTheme);
themeCookie.setMaxAge(60 * 60 * 24 * 30); // Must reset max age
themeCookie.setPath("/"); // Must set same path
response.addCookie(themeCookie); // Overwrites existing cookie
response.setContentType("text/html");
response.getWriter().println("<h2>Theme updated to: " + newTheme + "</h2>");
}
}Deleting Cookies
@WebServlet("/delete-cookie")
public class DeleteCookieServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// To delete a cookie: set maxAge to 0
Cookie userCookie = new Cookie("username", "");
userCookie.setMaxAge(0); // Immediately expires
userCookie.setPath("/"); // MUST match the original path!
response.addCookie(userCookie);
// Delete theme cookie
Cookie themeCookie = new Cookie("theme", "");
themeCookie.setMaxAge(0);
themeCookie.setPath("/");
response.addCookie(themeCookie);
response.setContentType("text/html");
response.getWriter().println("<h2>Cookies Deleted!</h2>");
response.getWriter().println("<a href=\"/read-cookie\">Verify</a>");
}
}⚠️ Critical: When deleting a cookie, thenameandpathmust match exactly. If the original cookie was set withpath=/app, you must delete it withpath=/app.
Cookie Attributes Reference
| Attribute | Method | Description |
|---|---|---|
| Name | Constructor | Cookie identifier (required) |
| Value | setValue() | Cookie data |
| Max-Age | setMaxAge() | Lifetime in seconds (-1 = session) |
| Path | setPath() | URL path scope |
| Domain | setDomain() | Domain scope |
| Secure | setSecure(true) | HTTPS only |
| HttpOnly | setHttpOnly(true) | No JavaScript access |
Max-Age Values
| Value | Meaning |
|---|---|
| Positive (e.g., 3600) | Cookie lives for that many seconds |
| 0 | Delete cookie immediately |
| -1 (default) | Session cookie (deleted when browser closes) |
Practical Example: Remember Me Login
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Check if remember-me cookie exists
String savedUser = getCookieValue(request, "remember_user");
String savedToken = getCookieValue(request, "remember_token");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (savedUser != null && validateToken(savedUser, savedToken)) {
// Auto-login
HttpSession session = request.getSession();
session.setAttribute("loggedInUser", savedUser);
response.sendRedirect("/dashboard");
} else {
// Show login form
out.println("<form method=\"POST\" action=\"/login\">");
out.println("<input name=\"username\" placeholder=\"Username\"><br>");
out.println("<input type=\"password\" name=\"password\" placeholder=\"Password\"><br>");
out.println("<label><input type=\"checkbox\" name=\"remember\"> Remember me</label><br>");
out.println("<button type=\"submit\">Login</button>");
out.println("</form>");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
String remember = request.getParameter("remember");
if (authenticate(username, password)) {
// Create session
HttpSession session = request.getSession();
session.setAttribute("loggedInUser", username);
// Set remember-me cookies if checked
if ("on".equals(remember)) {
String token = generateSecureToken();
Cookie userCookie = new Cookie("remember_user", username);
userCookie.setMaxAge(60 * 60 * 24 * 30); // 30 days
userCookie.setHttpOnly(true);
userCookie.setSecure(true);
userCookie.setPath("/");
Cookie tokenCookie = new Cookie("remember_token", token);
tokenCookie.setMaxAge(60 * 60 * 24 * 30);
tokenCookie.setHttpOnly(true);
tokenCookie.setSecure(true);
tokenCookie.setPath("/");
response.addCookie(userCookie);
response.addCookie(tokenCookie);
// Store token in database for validation
saveTokenToDatabase(username, token);
}
response.sendRedirect("/dashboard");
} else {
response.sendRedirect("/login?error=invalid");
}
}
private String getCookieValue(HttpServletRequest request, String name) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie c : cookies) {
if (c.getName().equals(name)) return c.getValue();
}
}
return null;
}
private boolean authenticate(String user, String pass) {
// Check against database
return "admin".equals(user) && "password123".equals(pass);
}
private boolean validateToken(String user, String token) {
// Validate token from database
return token != null && !token.isEmpty();
}
private String generateSecureToken() {
return java.util.UUID.randomUUID().toString();
}
private void saveTokenToDatabase(String user, String token) {
// Save to DB in real application
}
}Cookie Security Best Practices
| Practice | Why |
|---|---|
Set HttpOnly=true | Prevents XSS attacks from reading cookies |
Set Secure=true | Cookie only sent over HTTPS |
Set SameSite=Strict | Prevents CSRF attacks |
| Short expiration | Limits exposure window |
| Don't store sensitive data | Cookies are visible to user |
| Encrypt values | Protect against tampering |
| Validate on server | Never trust client data |
Cookies vs Sessions
| Feature | Cookies | Sessions |
|---|---|---|
| Storage | Client browser | Server memory |
| Size limit | 4KB per cookie | No practical limit |
| Security | Less secure (visible) | More secure (server-side) |
| Lifetime | Configurable | Until timeout/invalidation |
| Performance | No server memory used | Uses server memory |
| Data type | Strings only | Any Java object |
Common Mistakes
- Not matching path when deleting — Cookie won't be deleted
- Storing passwords in cookies — Never store sensitive data in cookies
- Not encoding cookie values — Special characters break cookies
- Exceeding 4KB limit — Browser silently drops oversized cookies
- Forgetting HttpOnly for auth cookies — XSS vulnerability
Interview Key Points
- Cookies are small data pieces stored on the client browser
- Maximum size: 4KB per cookie, typically 20 cookies per domain
setMaxAge(0)deletes;setMaxAge(-1)makes session cookie- HttpOnly prevents JavaScript access (XSS protection)
- Secure flag ensures HTTPS-only transmission
- Cookies are sent with EVERY request to the matching domain/path
Summary
In this chapter, we learned about Cookies in Servlets in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Cookies in Servlets.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, servlets, jsp, cookies
Related Java Master Course Topics