Reputation: 4532
How do I differentiate between multiple cookies set through my site? I am setting two kinds of cookies one to see if the user has visited the site or not and an other one for authentication. How do I differentiate between these two? I get both of them when someone accesses a page after authentication. Do I add extra information to the Cookie Value or is there some other way? I understand the setName() function will change the name (from jsessionid) for every cookie from then on. Am I correct?
Upvotes: 0
Views: 514
Reputation: 22973
Cookie is constructed as a name-value pair.
The getCookies() call of HttpServletRequest interface will return all the cookies in the request at hand.
You can iterate over all the cookies and find your requred cookie by checking the name using the getName call of the Cookie and retrieve it's value.
Upvotes: 0
Reputation: 24375
Look at this site for a cookie tutorial http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Cookies.html
You should be able to do a getName and check the name for the cookie. Here is a sample
public static String getCookieValue(Cookie[] cookies,
String cookieName,
String defaultValue) {
for(int i=0; i<cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName()))
return(cookie.getValue());
}
return(defaultValue);
}
You shoud create the cookie with something like this ...
Cookie searchStringCookie =
new LongLivedCookie("name", value);
response.addCookie(searchStringCookie);
Upvotes: 0
Reputation: 1108692
Regardless, to authenticate an user, I'd rather use the HttpSession
instead. On login, put the User
object as a session attribute so that you can just check the presence of the User
object in the session. The HttpSession
itself is backed by the JSESSIONID
cookie, the only difference is that the servletcontainer will manage this all for you transparently.
Upvotes: 1
Reputation: 4532
Wrong question. Cookie name is set when the cookie object is created.
Upvotes: 0