Wednesday, August 12, 2009

What are Cookies and how to use them?

A cookie is a bit of information sent by the Web server that can later be read back from the browser. Limitations for cookies are, browsers are only required to accept 20 cookies per site, 300 total per user , and they can limit each cookie's size to 4096 bytes (4K).

Cookie cookie = new Cookie("userId", "28764"); //Creating new Cookie

response.addCookie (cookie); // sending cookie to the browser

// Printing out all Cookies

Cookie[] cookies = request.getCookies();

if (cookies != null)
{
for (int i=0; i {
String name = cookies[i].getName();
String value = cookies[i].getValue();
}
}

Note : If you want to save special characters like "=", or spaces, in the value of the cookie, then makesure you URL encode the value of the cookie , before creating a cookie.

No comments:

Post a Comment