Cookies


HTTP Cookies are little pieces of data that a web application can store on the client machine of users visiting the web application. Typically up to 4 kilo bytes of data.
You can write cookies using the HttpServletResponse object like this:
Cookie cookie = new Cookie("myCookie", "myCookieValue");

response.addCookie(cookie);
As you can see, the cookie is identified by a name, "myCookie", and has a value, "myCookieValue". Thus, you can add many different cookies with different identifies (names). It's a bit like a Hashtable.
Whenever the the browser accesses the web application it submits the cookies stored on the client machine to the web application. Only cookies stored by the accessed web application are submitted. Cookies from other web applications are not submitted.
You can read the cookies via the HttpServletRequest like this:
Cookie[] cookies = request.getCookies();
Now you can iterate through the array of cookies and find the cookies you need.

Cookie Settings

A cookie has various settings you can modify. For instance, you can set the cookie expiration, which tell the browser how long time it should store the cookie on the client. You can also add comments to cookies, and set if the cookie should only be submitted over a secure line (HTTPS) etc. Check out the Cookie class for more details.

Cookie Use Cases

Cookies are most often used to store user specific information, like e.g. a unique user ID (for anonymous users which do not login), a session ID, or user specific setttings you do not want to store in your web applications database (if it has one).

No comments:

Post a Comment