LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 1618 min read

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.

What You Will Learn
  • 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

AspectCookieSession
Storage locationBrowser (client-side)Server (server-side)
LifespanSet by you, can persist for yearsEnds on timeout or invalidate()
Data sizeA few KB per cookiePractically unlimited (server memory)
Survives browser restartYes, if given a future expiryNo, unless persisted separately
Typical useRemember-me tokens, preferencesLogin state, cart, wizard progress

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.

Creating a Cookie
<%
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.

Reading a Cookie 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>
Rendered Output

Click Run to see what this code prints.

request.getCookies() Can Return null

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 That Persists for 30 Days
<%
Cookie rememberMe = new Cookie("lastUsername", "alexParker");
rememberMe.setMaxAge(60 * 60 * 24 * 30); // 30 days, in seconds
rememberMe.setPath("/");
response.addCookie(rememberMe);
%>

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.

Deleting a Cookie
<%
Cookie deleteCookie = new Cookie("lastUsername", "");
deleteCookie.setPath("/");
deleteCookie.setMaxAge(0); // deletes it
response.addCookie(deleteCookie);
%>

Common Mistakes

Avoid These 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.

Next Lesson →

Including Files (jsp:include)