Getting cookie in servlet

后端 未结 5 1774
情话喂你
情话喂你 2021-01-04 05:47

I\'m trying to get cookie in servlet using

Cookie[] cookie = request.getCookies();

but cookie is always null.

相关标签:
5条回答
  • 2021-01-04 05:52

    firstly ,you should create a cookie,and then add to response

    Cookie cookie = new Cookie(name,value);
    response.addCookie(cookie);
    
    0 讨论(0)
  • 2021-01-04 05:55

    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();
           }
       }
    
    0 讨论(0)
  • 2021-01-04 05:55

    I had the same problem and discovered the cause in my case was that I was using the browser built into Eclipse. This does not accept cookies. When I accessed the same JSP from chrome, it worked. Perhaps you are doing the same thing I did?

    It may also be the case that the browser you are using or your internet settings are set to reject cookies. Hope this helps you or any other visitor experiencing the same issue.

    0 讨论(0)
  • 2021-01-04 06:08

    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!

    0 讨论(0)
  • 2021-01-04 06:13

    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...

    0 讨论(0)
提交回复
热议问题