Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

httpservletrequest getCookies() or getHeader()

Tags:

java

servlets

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

like image 961
Yan Khonski Avatar asked Nov 13 '15 10:11

Yan Khonski


1 Answers

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. 
like image 59
Optional Avatar answered Oct 20 '22 03:10

Optional