简体   繁体   中英

Cookie handling with Servlet

I am having a problem of setting the data of a (persistent/cross browser session) cookie correctly inside a Servlet and the reading it in a Filter.

the code of the Servlet (running at log-in time) is:

    String encodedValue = new String(Base64
        .encodeBase64(req.getParameter("account").getBytes()));
    Cookie cookie = new Cookie("projectAuthenticationCookie", encodedValue );
    cookie.setMaxAge(24*60*60);
    cookie.setPath("/");
    res.addCookie(cookie);

This will get the cookie inside the response, but the when I read it within my filter with the following code:

    Cookie authenticationCookie = null;
    Cookie[] cookies = ((HttpServletRequest) request).getCookies();
    for (Cookie cookie : cookies){
        if ("projectAuthenticationCookie".equals(cookie.getName())) {
            authenticationCookie = cookie;
        }
    }

I only get the value I set right, all other fields are either null, empty or different. Max age for example always returns -1 and thus the cookie will never persist.

Cookie返回值

I tried setting the expires-header with:

    res.setDateHeader("Expires", System.currentTimeMillis() + 24*60*60*1000);

as I read that without a valid expires-header the session will timeout anyway (correct me if I am wrong), but that didn't help either...

One issue I am thinking of is that I am running on localhost (tried setting cookie.setDomain("localhost") but also no luck). My web server/serclet container is Jetty 7 but I do not think that this is relevant...

Any hints?

The fields other than name and value are not populated (and thus not meaningful) on cookies you get from a request.

These fields are intended to inform the browser about the max age; path, etc. of the cookie, but the browser doesn't send back this information to the server. The only time where it's important to have the correct max age, path, etc. is when you create a cookie and add it to the response. Use your browser to check if it stores the correct information instead of trying to find it at server-side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM