tags:

views:

347

answers:

4
+6  Q: 

Cookie getMaxAge

Hello I can't retrieve cookie maxage it always returns -1

Creating cookie:

Cookie securityCookie = new Cookie("sec", "somevalue");
securityCookie.setMaxAge(EXPIRATION_TIME);

Retrieve cookie:

Cookie[] cookies = request.getCookies();
if (cookies != null) {
    for(int i=0; i<cookies.length; i++) {
     Cookie cookie = cookies[i];
        if ("sec".equals(cookie.getName())){
      int age = cookie.getMaxAge();
        }
    }
}

i am always getting age = -1

also when i check in firefox cookie expiration i see strange date.

Thx

+1  A: 

The API says that -1 means until browser is running:

Returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown

What is the value of EXPIRATION_TIME constant?

Lazarin
+1  A: 

The value may be modified by the browser.

You create a cookie and want to set a max age. The cookie is sent to the browser. The browser may reject the cookie or ignore a max age too long for its policy. This modified cookie is sent back to your application.

Check your browser settings.

Arne Burmeister
A: 

Just for grins, can you retrieve the value of the cookie from the browser using javascript ?

Also, can you put a filter before your servlet/jsp so that you can check the value of the cookie after the servlet/jsp sets it ?

anjanb
+3  A: 

When a browser sends a cookie back to the origin server, it doesn't include any age. So it is logical that your "retrieve" code above does not receive a max age: it is not included in the request.

When the cookie is received from the server, the browser uses the max age parameter to determine how long the cookie should be kept; the age is never communicated back to the server, an expired cookie is simply discarded. When processing a request, if you want to renew the age of the cookie, reinclude the cookie in the response.

Also see the section "Sending Cookies to the Origin Server" in the RFC.

Bruno De Fraine
In other words, the browser doesn't share the maxAge with you. You don't get to know. Sorry.
Nathan Bubna