Get cookie value in java

Ready to use generic method:

public static Cookie getCookie(HttpServletRequest request, String name) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                return cookie;
            }
        }
    }
    return null;
}

You are using the wrong method for reading the cookies..

Cookie[] cookies = request.getCookies();

if (cookies != null) {
 for (Cookie cookie : cookies) {
   if (cookie.getName().equals("cookieName")) {
     //do something
     //value can be retrieved using #cookie.getValue()
    }
  }
}

use this. No need to detect the cookie for particular user just deactivate it.


Cookie[] cookies = request.getCookies();
int i = 0;
for (Cookie cookie : cookies ) {

  Sytem.out.println(cookies[i].getName());
  Sytem.out.println(cookies[i].getValue());

  i++;
}

Tags:

Java

Cookies