Cookies in JSP
Learn how to create, read, and expire cookies in JSP using the Cookie class, and understand how cookies differ from session attributes.
Introduction
Cookies are small pieces of data a server asks the browser to store and send back on future requests. You already met them indirectly — the JSESSIONID cookie is what makes HttpSession possible. This lesson shows you how to create and read your own cookies directly, useful for things like remembering a username or a UI preference across visits, even after the session has expired.
- How cookies differ from session attributes.
- How to create a cookie with javax.servlet.http.Cookie.
- How to read cookies sent by the browser.
- How to control a cookie's expiry and delete it.
Cookies vs Sessions
| Aspect | Cookie | Session |
|---|---|---|
| Storage location | Browser (client-side) | Server (server-side) |
| Lifespan | Set by you, can persist for years | Ends on timeout or invalidate() |
| Data size | A few KB per cookie | Practically unlimited (server memory) |
| Survives browser restart | Yes, if given a future expiry | No, unless persisted separately |
| Typical use | Remember-me tokens, preferences | Login state, cart, wizard progress |
Creating a Cookie
A cookie is a name-value pair wrapped in the Cookie class. After constructing it, you add it to the response so the browser knows to store it.
<% Cookie usernameCookie = new Cookie("lastUsername", "alexParker"); usernameCookie.setPath("/"); // available across the whole app response.addCookie(usernameCookie);%><p>Cookie set for next visit.</p>Reading Cookies
Incoming cookies are read from the implicit request object as an array — there is no getCookie("name") shortcut, so you loop through and match by name.
<% String lastUsername = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie c : cookies) { if (c.getName().equals("lastUsername")) { lastUsername = c.getValue(); break; } } }%><p>Welcome back, <%= (lastUsername != null) ? lastUsername : "Guest" %>!</p>Click Run to see what this code prints.
If the browser sent no cookies at all, getCookies() returns null rather than an empty array. Always null-check before looping, as shown above.
Setting Expiry
By default, a cookie with no expiry set is a session cookie — it disappears when the browser closes. To make it persist, call setMaxAge() with a lifetime in seconds.
<% Cookie rememberMe = new Cookie("lastUsername", "alexParker"); rememberMe.setMaxAge(60 * 60 * 24 * 30); // 30 days, in seconds rememberMe.setPath("/"); response.addCookie(rememberMe);%>Deleting a Cookie
There is no delete() method — you delete a cookie by re-sending one with the same name and path, but with maxAge set to zero. The browser sees this and immediately removes the matching cookie.
<% Cookie deleteCookie = new Cookie("lastUsername", ""); deleteCookie.setPath("/"); deleteCookie.setMaxAge(0); // deletes it response.addCookie(deleteCookie);%>Common Mistakes
- Forgetting to set a matching path when deleting a cookie — if the path does not match how it was created, the delete silently fails.
- Storing sensitive data like passwords in a cookie; cookies are visible and editable by the user.
- Not null-checking request.getCookies() before looping over it.
- Confusing setMaxAge(0) (delete now) with setMaxAge(-1) (session cookie, deleted on browser close).
Best Practices
- Keep cookie values small and non-sensitive — an ID or token, not personal data.
- Always set an explicit path so the cookie behaves predictably across the app.
- Mark authentication-related cookies as HttpOnly and Secure at the servlet or filter level when possible.
- Use sessions for anything that must stay strictly server-side.
Frequently Asked Questions
Yes, via the implicit cookie object, for example ${cookie.lastUsername.value}.
Browsers typically limit around 50 cookies per domain and about 4KB per cookie, so keep usage light.
No. Cookie values are plain text unless you encrypt them yourself before storing.
Key Takeaways
- Cookies live in the browser and can persist across visits, unlike sessions.
- Create them with new Cookie(name, value) and response.addCookie().
- Read them by looping request.getCookies() and matching the name.
- Delete a cookie by re-adding it with the same name/path and maxAge(0).
Summary
Cookies give you a lightweight, client-side complement to server-side sessions. With both tools in hand, you are ready to look at page composition — how large JSP applications reuse a common header and footer instead of duplicating markup everywhere.