Getting cookie in servlet

76,811

Solution 1

According to docs getCookies() Returns an array containing all of the Cookie objects the client sent with this request. This method returns null if no cookies were sent.

Did you add the cookie correctly? If yes, you should be able to iterate through the list of cookies returned with

Cookie[] cookies = request.getCookies();

for (int i = 0; i < cookies.length; i++) {
  String name = cookies[i].getName();
  String value = cookies[i].getValue();
}

If no...

Cookies are added with the addCookie(Cookie) method in the response object!

Solution 2

SET COOKIE

  Cookie cookie = new Cookie("cookiename", "cookievalue");
  response.addCookie(cookie);

GET COOKIE

  Cookie[] cookies = request.getCookies();
  if(cookies != null) {
      for (int i = 0; i < cookies.length; i++) {
          cookie=cookies[i]
          String cookieName = cookie.getName();
          String cookieValue = cookie.getValue();
       }
   }

Solution 3

Are you sure the client supports cookies? because if it is configure to NOT accept cookies, you will never get them back on a following request...

Share:
76,811
Anatoly
Author by

Anatoly

Updated on March 07, 2020

Comments

  • Anatoly
    Anatoly about 4 years

    I'm trying to get cookie in servlet using

    Cookie[] cookie = request.getCookies();
    

    but cookie is always null.

    So I set them from another servlet and they appear in browser preferences.

    Cookie cookie = new Cookie("color", "cyan");
    cookie.setMaxAge(24*60*60);
    cookie.setPath("/");
    response.addCookie(cookie);
    

    I don't understand what's wrong?

    • adarshr
      adarshr almost 12 years
      Where are you calling this code?
    • John Watts
      John Watts almost 12 years
      Does the browser access this other servlet using the same domain name, protocol and port (e.g. example.com:80).
  • Anatoly
    Anatoly almost 12 years
    So I mean that I add cookie from another servlet and that servlet really adds cookie, but when i"m trying to get request.getCookie() returns null.
  • Anatoly
    Anatoly almost 12 years
    I adds cookie this way from another servlet
  • gcochard
    gcochard almost 12 years
    @Anatoly Is the other servlet on your same domain and subdomain?
  • hectorg87
    hectorg87 over 10 years
    Note the "This method returns null if no cookies were sent.", The given code will fail with NullPointerException when doing cookies.length if getCookies() returns null.
  • Prajwal Bhat
    Prajwal Bhat over 7 years
    able to read only the alphabets, not reading the alphanumerics or special symbols ? What may be the cause ?
  • Alberto Acuña
    Alberto Acuña over 5 years
    what about add timelife to the cookie? it is possible¿?