java - 我设置了cookie的max age,但是cookie依然在关闭游览器后消失了
迷茫
迷茫 2017-04-18 10:51:59
0
3
1367

我设置了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。

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(3)
伊谢尔伦

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

阿神

It’s a browser problem. . . . .

巴扎黑

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!