8 Years
Discussion Span
Last Post by nsisupalan

From a tutorial I have:

For example, to create a cookie named userID with a value a1234, you would use the following.

Cookie c = new Cookie("userID", "a1234");

If you create a cookie and send it to the browser, by default it is a session-level cookie: a cookie that is stored in the browser's memory and deleted when the user quits the browser. If you want the browser to store the cookie on disk, use setMaxAge with a time in seconds, as below.

c.setMaxAge(60*60*24*7); // One week

To send the cookie, insert it into a Set-Cookie HTTP response header by means of the addCookie method of HttpServletResponse

Cookie userCookie = new Cookie("user", "uid1234");
userCookie.setMaxAge(60*60*24*365); // Store cookie for 1 year

To send a cookie to the client, you create a Cookie, set its maximum age (usually), then use addCookie to send a Set-Cookie HTTP response header. To read the cookies that come back from the client, you should perform the following two tasks, which are summarized below and then described in more detail in the following subsections.

Call request.getCookies. This yields an array of Cookie objects.

Loop down the array, calling getName on each one until you find the cookie of interest. You then typically call getValue and use the value in some application-specific way.

String cookieName = "userID";
Cookie[] cookies = request.getCookies();
if (cookies != null) {
  for(int i=0; i<cookies.length; i++) {
    Cookie cookie = cookies[i];
    if (cookieName.equals(cookie.getName())) {
This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.