Cookies are the textual information that is stored in key-value pair format to the client's browser during multiple requests. It is one of the state management techniques in session tracking. Basically, the server treats every client request as a new one so to avoid this situation cookies are used. When the client generates a request, the server gives the response with cookies having an id which are then stored in the client's browser. Thus if the client generates a second request, a cookie with the matched id is also sent to the server. The server will fetch the cookie id, if found it will treat it as an old request otherwise the request is considered new.
👁 Cookie creation in Client-Server request-response model
Using Cookies in Java
- In order to use cookies in java, use a Cookie class that is present in javax.servlet.http package.
- To make a cookie, create an object of Cookie class and pass a name and its value.
- To add cookie in response, use addCookie(Cookie) method of HttpServletResponse interface.
- To fetch the cookie, getCookies() method of Request Interface is used.
Methods in Cookies
- clone(): Overrides the standard java.lang.Object.clone method to return a copy of this Cookie.
- getComment(): Returns the comment describing the purpose of this cookie, or null if the cookie has no comment.
- getDomain(): Gets the domain name of this Cookie.
- getMaxAge(): Gets the maximum age in seconds of this Cookie.
- getName(): Returns the name of the cookie.
- getPath(): Returns the path on the server to which the browser returns this cookie.
- getSecure(): Returns true if the browser is sending cookies only over a secure protocol, or false if the browser can send cookies using any protocol.
- getValue(): Gets the current value of this Cookie.
- getVersion(): Returns the version of the protocol this cookie complies with.
- setValue(String newValue): Assigns a new value to this Cookie.
- setVersion(int v): Sets the version of the cookie protocol that this Cookie complies with.
Example
The name of the Institute is passed to Servlet 2 from Servlet 1 using Cookies.
👁 Index.html output👁 Servlet1.java output