10

I want to accept data from a client. What are the pros and cons of each approach?

HttpServletRequest request = retriveRequest();
Cookie [] cookies = request.getCookies();
for (Cookie cookie : cookies) {
     if ("my-cookie-name".equals(cookie.getName())) {
          String value = cookie.getValue();
         //do something with the cookie's value.
     }
}

or

String request.getHeader("header-name");

As I read How are cookies passed in the HTTP protocol?

Cookies are passed as HTTP headers, both in the request (client -> server), and in the response (server -> client).

Yan Khonski
  • 12,225
  • 15
  • 76
  • 114

1 Answers1

13

getCookies, frees you from parsing the Cookie header string, and creating a java object out of it. Otherwise you will have to do something like:

String rawCookie = request.getHeader("Cookie");
String[] rawCookieParams = rawCookie.split(";");
for(String rawCookieNameAndValue :rawCookieParams)
{
  String[] rawCookieNameAndValuePair = rawCookieNameAndValue.split("=");
}
// so on and so forth. 
Optional
  • 4,387
  • 4
  • 27
  • 45
  • I agree with you, thanks. How about this case? What if I want just to pass data. Either I pass it via cookie or just header, does not matter. for example String str = request.getHeader("my-param"); And I do not need to parse this string because it will be value I need. – Yan Khonski Nov 13 '15 at 11:49
  • And one more thing, cookies are useful to store data from a site and send this data after some time. If I exchange with the server without cookies, where do I store say "locale-param", "preferred theme" of stuff like this? – Yan Khonski Nov 13 '15 at 11:54
  • 1
    Locale should go to Accept-Language field e.g en/ja etc... For custom headers you can define your own custom headers as well. – Optional Nov 16 '15 at 08:21
  • How to create a `request` object of `HttpServletRequest` ? – Kavipriya Apr 05 '17 at 11:16
  • @Kavipriya request is just a variable name for HttpServletRequest. Its the same – Optional Apr 06 '17 at 08:49