Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Is there a simple way to get cookie by name?

Tags:

java

cookies

I've searched for solutions on how to get cookies by their name and all solutions point to using for-loops and if statements. See code below.

for (Cookie cookie : cookies) {
    if (cookie.getName().equals("<NAME>")) {
        // do something here
    } 
    if (cookie.getName().equals("<ANOTHER_NAME>")) {
        // do something here
    } 
    // and so on...
}

Is there any simpler way to get the value by their name without having to do the loops and if's?

I need to make some "certain" processing for certain cookies I would want to retrieve Plus, I don't want to traverse through every cookie! There could be 10 or more and all I need is just three or something.

like image 708
Tech Newbie Avatar asked Mar 11 '15 02:03

Tech Newbie


People also ask

Which method would you use to get the cookies from the response object?

public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in response object. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from the browser.


1 Answers

The logic (as suggested by Matt Ball in the comments) would be:

// ...
Map<String, Cookie> cookieMap = new HashMap<>();
for (Cookie cookie : cookies) {
    cookieMap.put(cookie.getName(), cookie);
}

Cookie firstRequiredCookie = cookieMap.get("<NAME>");
// do something with firstRequiredCookie 
Cookie nextRequiredCookie = cookieMap.get("<ANOTHER_NAME>");
// do something with nextRequiredCookie 
// ...
like image 178
KrishPrabakar Avatar answered Oct 15 '22 16:10

KrishPrabakar