In the Java servlet, cookie.getMaxAge () always returns -1

If I set a cookie with setMaxAge () in the future, when I read the cookie in memory in a subsequent request, getMaxAge () will return me -1. I checked the actual cookie using the Chrome settings and inspector, and I can check if the expiration date expires after 60 days.

static public void setHttpCookie(HttpServletResponse response, String payload) { Cookie c = new Cookie(COOKIE_NAME, payload); c.setMaxAge(60*86400); // expire sixty days in the future c.setPath("/"); // this cookie is good everywhere on the site response.addCookie(c); } static public String checkForCookie(HttpServletRequest req) { Cookie[] cookies = req.getCookies(); if ( cookies != null ) { for ( Cookie c : cookies ) { if ( COOKIE_NAME.equals(c.getName()) ) { int maxAge = c.getMaxAge(); logger.debug("Read back cookie and it had maxAge of {}.", maxAge); String payload = c.getValue(); return payload; } } } return null; } 

Why does c.getMaxAge () always return -1?

+5
java cookies servlets
source share
1 answer

The browser does not send cookie attributes such as path and age. It returns only the name and value. If the maximum age has expired, the browser will not send cookies in any way. If the path is not covered by the request URI, the browser will still not send a cookie.

If you really need to determine the age of the cookies after you set the cookie, then you must remember it yourself in another place at the moment you set the cookie, for example, in the database table associated with the logged in user and name cookie, for example.

This issue is not related to Java / Servlets. It is like an HTTP cookie. You will have the same problem in other web programming languages. See also the following excerpt from Wikipedia (emphasis mine).

Cookie attributes

In addition to the name-value pair, servers can also set these cookie attributes: cookie domain, path, expiration date or maximum age, security flag and HttpOnly flag. Browsers will not send cookie attributes back to the server. They will only send a cookie name-value pair . The cookie attributes are used by browsers to determine when to delete a cookie, block a cookie, or send a cookie (name / value pair) to the servers.

+10
source share

All Articles