How to use Cookies with Java Servlets

Cookies are pieces of data that an HTTP client can be asked to associate with a web site or subsection of a web site1. Whenever the client requests a page, it sends along with the request any cookies that it was previously asked to associate with that web site and/or page. Cookies are used for cases where we need to "maintain state" across HTTP requests. In the real world, this typically means for the following purposes:

It's actually not so common to manipulate cookies directly. In the common case of handling sessions, the Java Servlet framework provides a Session API. If you're implementing sessions, it's generally a good idea to use the API designed for that purpose, for a few reasons:

All that said, if you do want to manually set and read cookies from a Java Sevlet, then a Cookie API is provided.

1. Technically, cookies are restricted to a particular domain or subdomain and potentially a specific path of that domain/subdomain.

If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.