How to get the Cookies from listeners?

263 views Asked by At

I made an app and I want to get cookies as soon as there is new session. I tried it with the session listener but didn't work. I tried it with the request listener but got a null in cookies array. this is the code from request listener and it gets me null every time

public void requestInitialized(ServletRequestEvent sre) {
    
    HttpServletRequest req=(HttpServletRequest)sre.getServletRequest();
    if(req.getSession().isNew())
    {
        Cookie c[]=req.getCookies();
        try
        {
            for (Cookie co:c)
            {
                System.out.println(co.getName());
                System.out.println(co.getValue());
            }
        }
        catch(Exception e)
        {
            System.out.println("error: "+ e.getMessage());
        }
    }
}
2

There are 2 answers

0
Illya Kysil On

The HttpServletRequest.getCookies() returns cookies provided in the request - as described in the HttpServletRequest's javadoc.

When servlet container creates a new session, it usually means that either no cookies were provided (session is unknown) or there was a session cookie, but the session itself has been expired.

Please check section 7.1 Session Tracking Mechanisms of the Java™ Servlet Specification for the complete explanation of the standard session semantics and lifecycle.

0
Hossam Tag El Din On

I figured it out , the problem was with chrome. it consider the cookie as session cookie until I added header "Expires" to the response