How can I specify which kind of cookies (single-session cookies or persistent cookies) I want to use ?

Vincent Cirel

Refer to Sun's Servlet API Reference at
and take a look at Cookie class constructor and methods.

In general:

// create the cookie
Cookie c = new Cookie("stringname","stringvalue");

// set Age

// send it back with the HTTP response
  • Setting iAge < 0 indicates the default behavior of "death to the cookie upon browser exit"
  • Setting iAge = 0 indicates that the browser should delete the cookie immediately.
  • Setting iAge > 0 specifies the max age of the cookie before expiration (in seconds) = iAge

You could also use :

response.setHeader("Set-Cookie","name=value; expires=date");
where date = Wdy, DD-Mon-YYYY HH:MM:SS GMT (ie. Monday, 12-Jun-2000 17:24:00 GMT).

One reason I can think of where you might want to use the setHeader method is if you need to set an expiration date > 68.1 years future. The largest +(int) value allowed is 2147483647 or about 68.1 years.

Note that in either case cookies are sent back using HTTP headers. Therefore, you should add them to the response BEFORE you send any content back to the browser.

See also How do I setup a cookie to expire after a certain time?