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...
Author by
Anatoly
Updated on March 07, 2020Comments
-
Anatoly about 4 years
I'm trying to get cookie in servlet using
Cookie[] cookie = request.getCookies();
but
cookie
is alwaysnull
.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 almost 12 yearsWhere are you calling this code?
-
John Watts almost 12 yearsDoes the browser access this other servlet using the same domain name, protocol and port (e.g. example.com:80).
-
-
Anatoly almost 12 yearsSo 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 almost 12 yearsI adds cookie this way from another servlet
-
gcochard almost 12 years@Anatoly Is the other servlet on your same domain and subdomain?
-
hectorg87 over 10 yearsNote 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 over 7 yearsable to read only the alphabets, not reading the alphanumerics or special symbols ? What may be the cause ?
-
Alberto Acuña over 5 yearswhat about add timelife to the cookie? it is possible¿?