Why does cookie.getMaxAge() always get -1?

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;
}

The browser does not send cookie attributes such as path and age. It just returns the name and value. If max expires, the browser will not send the cookie. If the browser path is not overwritten by the new URI, then the browser will not send the cookie anyway. If you really need to determine the age of the cookie after it is set, then you should remember it elsewhere when you set the cookie, for example in a database table, associated with the logged in user and the cookie name. This problem has nothing to do with ava servlet. This is what is specified by the HTTP cookie.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325551358&siteId=291194637