Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cookie getMaxAge

Tags:

java

servlets

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

like image 764
dcave555 Avatar asked Oct 07 '08 09:10

dcave555


People also ask

What is cookies in j2ee?

public class Cookie extends Object implements Cloneable, Serializable. Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used for session management.

What is servlet in simple words?

A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers.

Which method is used to get the cookie from the request?

Cookie objects by calling the getCookies() method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value.


2 Answers

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.

like image 83
Bruno De Fraine Avatar answered Sep 30 '22 20:09

Bruno De Fraine


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?

like image 34
Lazarin Avatar answered Sep 30 '22 19:09

Lazarin