Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting cookie in servlet

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?

like image 796
Anatoly Avatar asked Jun 15 '12 08:06

Anatoly


People also ask

How do you set and get cookies in servlet?

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.

What is a cookie in servlet?

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.

Which of the following code is use to get cookies in servlet?

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?

How do I add a cookie to an HTTP response?

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.


2 Answers

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!

like image 56
gotomanners Avatar answered Sep 22 '22 10:09

gotomanners


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();
       }
   }
like image 22
dhan rajr Avatar answered Sep 20 '22 10:09

dhan rajr