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指定的。