A Cookie is a small piece of information created at server side and stored at the cache of the browser(at client side). A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.
Here when the first request sends from client to the server, then at the server side cookie is created. Then the server sends the response along with cookie to the client. When the second request sends from that particular client then the request goes along with cookie. Then the server recognizes the user as old user by cookie.
In Servlet, there are two types of cookie, such as non-persistent cookie and persistent cookie.
Non-persistent cookie is valid for single session only. It is removed each time when user closes the browser and persistent cookie is valid for multiple session. It is removed only if user logout or signout.
We can create cookie by creating Cookie object. Cookie is an in-built class present in Servlet API. Cookies are added to response object by invoking the addCookie() method, and we can get the cookie by invoking getCookies() method.