我设置了cookie的最大年龄,但关闭浏览器后cookie仍然不存在

时间:2017-03-25 12:39:52

标签: java spring-mvc cookies

我设置了cookie的最大年龄,但关闭浏览器后cookie仍然不存在。我的控制器:

package com.jiaotong114.jiaotong.controller;
@Controller
@RequestMapping("/")
public class CityIndex { 
@RequestMapping(value="/city/{cityName}", method = RequestMethod.GET)
public String printHello(ModelMap model, @PathVariable("cityName") String cityName, HttpServletRequest request, HttpServletResponse response) {

    Cookie[] c = request.getCookies();
    boolean isNew = true;
    for(int i = 0; i < c.length; i++) {
        if(c[i].getName().equals("cityName")) {
            c[i].setValue(cityName);
            c[i].setMaxAge(365 * 24 * 60 * 60);
            response.addCookie(c[i]);
            isNew = false;
        }
    }
    if(isNew) {
        Cookie cityNameCookie = new Cookie("cityName", cityName);
        cityNameCookie.setMaxAge(365 * 24 * 60 * 60);
        response.addCookie(cityNameCookie);
    }
    request.getSession().setAttribute("cityName", cityName);
    return "index";
}
}

访问http://localhost:8080/city/shanghai来运行此控制器。 然后将cookie添加到客户端。 图片: the cookie of client after entering the url

到期时间为一年。 (正如我在代码中设置的那样:cityNameCookie.setMaxAge(365 * 24 * 60 * 60);

但是当我关闭了布料机时,重新打开它并进入http://localhost:8080。然后我发现我的cityName cookie消失了。

enter image description here

我在代码中设置了cookie的最大年龄时间,为什么关闭浏览器后cookie会消失?

1 个答案:

答案 0 :(得分:0)

最后我找出了问题。

使用cookie.setPath("/")将cookie的路径设置为应用程序的根目录。这使得cookie可用于所有页面。如果您没有设置此设置,则cookie的路径将是请求路径,这意味着您只能在访问cookie或其子路径时访问cookie。