-1

I set the max age of cookie, but the cookie still does not exist after closing browser. My 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";
}
}

Run this controller by accessing http://localhost:8080/city/shanghai. Then the cookie added to the client. image: the cookie of client after entering the url

The expiry time is one year. (as I set in code: cityNameCookie.setMaxAge(365 * 24 * 60 * 60);)

But when I closed the brower, reopened it and entered the http://localhost:8080. Then I found my cityName cookie disappear.

enter image description here

I set the max age time of cookie in the code, why did the cookie disappear after closing browser?

T-Heron
  • 5,385
  • 7
  • 26
  • 52
inter18099
  • 103
  • 10
  • 2
    The session expired? – Roman C Mar 25 '17 at 12:41
  • @Roman C I use 「cityNameCookie.setMaxAge(365 * 24 * 60 * 60);」 to set expired time one year. theoretically speaking the cookie should exists after closing brower and closing session. – inter18099 Mar 25 '17 at 12:50
  • If you close browser you can't use the same session again. – Roman C Mar 25 '17 at 12:53
  • @Roman C Yes, but the cookie should exists even though the session is closed because I called the setMaxAge() method and set that the existing time is one year. The default setting is that cookie will disappear after closing browser(closing session), but I override the default setting by calling setMaxAge(). – inter18099 Mar 25 '17 at 13:00
  • Why do you think you set a cookie if the session expired? – Roman C Mar 25 '17 at 13:07
  • @Roman C check this: http://stackoverflow.com/questions/8894243/why-cookies-dont-expire-after-closing-browser – inter18099 Mar 25 '17 at 13:12

1 Answers1

1

Finally I figure out the problem.

Use cookie.setPath("/") to set the path of cookie to root of the application. This make cookie available to all page. If you don't set this setting, the path of cookie will be the request path, this means you only can access the cookie when access the path of cookie or subpath of it.

inter18099
  • 103
  • 10