search

Home  >  Q&A  >  body text

java - 我设置了cookie的max age,但是cookie依然在关闭游览器后消失了

我设置了cookie的max age,但是cookie依然在关闭游览器后消失了。
我的controller:

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/sh...调用这个controller,可以从图片看到cookie已经被成功添加到客户端了,时间是一年。

但是当我关闭了游览器,重新打开,访问http://localhost:8080,然后发现我的cookie不见了。见图2。

迷茫迷茫2802 days ago1431

reply all(3)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:53:59

    The problem is solved, cookie.setPath("/") is set

    reply
    0
  • 阿神

    阿神2017-04-18 10:53:59

    It’s a browser problem. . . . .

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 10:53:59

    cookie是由多个属性决定的,我猜max-age is just one of them.

    reply
    0
  • Cancelreply