How to check if cookie exists or not using JSP code?
How to check if cookie exists or not using JAVA/JSP?
This codes looks with all cookies which is problem for me so i directly wanted to check if particular cookies exists or not.
Open the cookie jar and look in. If there are cookies, then they exist.
Except for oatmeal raisin, those type of cookies don't exist to me. I look into the cookie jar and if its full of oatmeal raisin, no cookies exist.
On HttpServletRequest there is a method called getCookies that returns an array of Cookie(s).
You should then be able to look through that array to see if the cookie you want is present or not.
To set a Cookie you will need to use the addCookie(Cookie) method on HttpServletResponse.
The only method available on HttpServletRequest that deals with Cookies is getCookies(), which returns an array of Cookies.
You will have to loop though the Cookies like the example in the above link to figure out if the Cookie you're interested in is there or not.
You could write a helper method if needed and have something like a HttpUtils class.
Yes we have the array and loop through it and you are able to track it down, but I was wondering if we have any solution to avoid array loop and directly check the cookie.
if (cookie.name("my_cookie")) == -1)
The browser sends all cookies so you don't really have much choice.
So what are you trying to do exactly with that cookie value? Are you performing this cookie check in many different jsp files? Is this cookie value required on every page?
You might consider using a filter to check for the cookie.
You could do
boolean cookiePresent = Arrays.toList( request.getCookies() ).contains( "cookie_name" );
but the array will still be looped through, behind the scenes (with this code, twice, I think).
If it's something you check often, set a session attribute to denote that you checked. Then you only have to 'pay' for the check once, after that, it's as efficient as it's going to get.
I'm so tired of those jokes... wish they would name it other than cookie.... :nono::nono::nono:
looking for JSP logic instead of JS
We gave you JSP logic, more accurately, we gave you Java logic that can be used in a JSP.