Tony
Tony

Reputation: 3805

Cookie max age in Java

What is the difference between this:

cookie.setMaxAge(0);

and this

cookie.setMaxAge(-1);

Does first make it removed?

Upvotes: 9

Views: 36000

Answers (4)

the-petrolhead
the-petrolhead

Reputation: 617

cookie.setMaxAge( 0 ) will delete the cookie right away.

cookie.setMaxAge( -1 ) will preserve the cookie for a while and delete the cookie when the browser exits.

For relevant information refer the API Documentation.

Upvotes: 2

Hirak
Hirak

Reputation: 3649

Assuming we are talking about javax.servlet.http.Cookie

This is what Javadoc says

setMaxAge public void setMaxAge(int expiry)

Sets the maximum age in seconds for this Cookie.

A positive value indicates that the cookie will expire after that many seconds have passed. Note that the value is the maximum age when the cookie will expire, not the cookie's current age.

A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits.

A zero value causes the cookie to be deleted.

Upvotes: 9

IsidroGH
IsidroGH

Reputation: 2037

A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.

http://docs.oracle.com/javaee/6/api/javax/servlet/http/Cookie.html#setMaxAge%28int%29

Upvotes: 7

nanofarad
nanofarad

Reputation: 41281

From RFC 6265:

If delta-seconds is less than or equal to zero (0), let expiry-time be the earliest representable date and time. Otherwise, let the expiry-time be the current date and time plus delta-seconds seconds.

Therefore, both have the cookie expire as soon as possible on a compliant user-agent.

However, in practice, negative values imply session cookies.

Upvotes: 2

Related Questions