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?
To make a cookie, create an object of Cookie class and pass a name and its value. To add cookie in response, use addCookie(Cookie) method of HttpServletResponse interface. To fetch the cookie, getCookies() method of Request Interface is used.
A cookie is a small piece of information that is persisted between the multiple client requests. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.
getCookies() returns an array containing all of the Cookie objects the client sent with this request. Q 23 - Which of the following code is used to get names of the attributes in servlet?
To add a new cookie, use HttpServletResponse. addCookie(Cookie). The Cookie is pretty much a key value pair taking a name and value as strings on construction.
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!
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With