simplecode — 2010-08-18T02:23:35-04:00 — #1
How to check if cookie exists or not using JSP code?
simplecode — 2010-08-18T02:34:38-04:00 — #2
How to check if cookie exists or not using JAVA/JSP?
ernie1 — 2010-08-18T03:58:42-04:00 — #3
simplecode — 2010-08-18T09:34:07-04:00 — #4
This codes looks with all cookies which is problem for me so i directly wanted to check if particular cookies exists or not.
hooknc — 2010-08-18T11:47:15-04:00 — #5
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.
hooknc — 2010-08-18T11:49:03-04:00 — #6
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.
hooknc — 2010-08-18T11:53:04-04:00 — #7
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.
simplecode — 2010-08-19T03:41:50-04:00 — #8
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)
rozner — 2010-08-19T05:03:36-04:00 — #9
The browser sends all cookies so you don't really have much choice.
hooknc — 2010-08-19T11:59:27-04:00 — #10
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.
rushiku — 2010-08-20T00:23:05-04:00 — #11
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.
sg707 — 2010-08-20T14:47:22-04:00 — #12
I'm so tired of those jokes... wish they would name it other than cookie.... :nono::nono::nono:
simplecode — 2010-08-31T01:23:47-04:00 — #13
looking for JSP logic instead of JS
rushiku — 2010-08-31T08:50:03-04:00 — #14
We gave you JSP logic, more accurately, we gave you Java logic that can be used in a JSP.