为什么 cookie.getMaxAge() 总是得到 -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;
}

  

浏览器不发送cookie属性,比如路径和年龄。它只返回名称和值。如果max过期了,浏览器就不会发送cookie了。如果浏览器路径没有被新URI覆盖,那么浏览器无论如何也不会发送cookie。如果你真的需要在设置cookie之后确定cookie的年龄,那么在你设置cookie时,你应该在其他地方记住它,例如在数据库表中,与登录的用户和cookie名称相关联。这个问题与ava servlet无关。这就是由HTTP cookie指定的。

原文地址:https://www.cnblogs.com/liqing-weikeyuan/p/8192768.html