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?
Pav
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.
Wrong question. Cookie name is set when the cookie object is created.
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);
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.
Related
If I set a cookie with a setMaxAge() well into the future, when I read the cookie back into memory in a subsequent request, the getMaxAge() gives me back a -1. I have checked the actual cookie via Chrome's settings, and inspector, and I can verify that the expiration date is indeed set 60 days in the future.
static public void setHttpCookie(HttpServletResponse response, String payload) {
Cookie c = new Cookie(COOKIE_NAME, payload);
c.setMaxAge(60*86400); // expire sixty days in the future
c.setPath("/"); // this cookie is good everywhere on the site
response.addCookie(c);
}
static public String checkForCookie(HttpServletRequest req) {
Cookie[] cookies = req.getCookies();
if ( cookies != null ) {
for ( Cookie c : cookies ) {
if ( COOKIE_NAME.equals(c.getName()) ) {
int maxAge = c.getMaxAge();
logger.debug("Read back cookie and it had maxAge of {}.", maxAge);
String payload = c.getValue();
return payload;
}
}
}
return null;
}
Why does c.getMaxAge() always return -1?
The browser does not send cookie attributes like path and age back. It only sends the name and the value back. If the max age is expired, then the browser won't send the cookie anyway. If the path is not covered by request URI, then the browser won't send the cookie anyway.
If you really need to determine the cookie's age after you have set the cookie, then you should remember it yourself elsewhere at the moment you've set the cookie, such as in a database table, associated with the logged-in user and cookie name, for example.
This problem is unrelated to the Java/Servlets. It's just how HTTP cookie is specified. You'd have exactly the same problem in other web programming languages. See also the following extract from Wikipedia (emphasis mine).
Cookie attributes
Besides the name–value pair, servers can also set these cookie attributes: a cookie domain, a path, expiration time or maximum age, Secure flag and HttpOnly flag. Browsers will not send cookie attributes back to the server. They will only send the cookie’s name-value pair. Cookie attributes are used by browsers to determine when to delete a cookie, block a cookie or whether to send a cookie (name-value pair) to the servers.
The best what you can possibly do is to bump the cookie's max age every time during e.g. login. You can easily achieve this by setting exactly the same cookie once more (especially exactly the same domain/path/name). It will overwrite the existing cookie. This is usually done that way on so-called "Remember me" cookies.
I want to delete a Cookie through Java Code which I have written like,
Cookie[] cookies = request.getCookies(); //request - HttpServletRequest
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("cam_passport")) {
cookies[i].setMaxAge(0);
cookies[i].setValue("");
response.addCookie(cookies[i]);
}
}
I am getting the list of cookies in the "cookies" object but not the required one "cam_passport".
What I have observed is, the PATH of this Cookie is different when I checked in Mozilla.
Where as, the list of Cookies which I am getting in my 'cookies' object have their path as "/".
And, for this "cam_passport" cookie, path is "/cognos10".
I need the above cookie to be deleted at one instance every time. How can I get the Cookies of different path like the above one?
You need to send a redirect to that path, perhaps along with a request parameter. You can then in a servlet or filter which is mapped on exactly that path obtain the cookie and delete it, if necessary based on presence of the request parameter. Finally you can redirect back to the original URL, if necessary based on a request parameter.
In the future, use cookie.setPath("/") during creating the cookie if you need the cookie to be available throughout the entire web application.
I have a site name www.goo.com and i used to save cookie without declaring domain name when creating the cookie.
Now, i want to add sub domain foo.goo.com
I save the cookie in the domain and not in the sub domain.
There are 2 problems:
I want to delete the old cookie.
I tried to do 'cookie.setMaxAge(0)' already and the problem is that in Firefox and chrome it do not work. it work only in IE.
why? and what i can do about it?
When i do
Cookie[] cookie = request.getCookies();
if (cookie != null) {
for (int i = 0; i < cookie .length; i++) {
cookie[i].getDomain(); //here i get null.why?
}
}
Why i get null in the getDomain() line?
Edit:
i tried to add this line:
response.setContentType("text/html");
to send the content type.
I also tried to send the cookie through the response.
Someone have another idea, for the 2 problems the presents here?
Answered here: How do you remove a Cookie in a Java Servlet (you need to send a text/html content type)
When a client sends cookies to the server, it only sends the name/value. The other fields are only available when setting the cookie.
I have a domain 'www.foo.com' and I want to create sub domain 'test.foo.com'.
In order to combine those 2 domains to share only one cookie I set the cookie to be like that:
Cookie cookie = new Cookie("myCookie", "myValue");
cookie.setMaxAge(60 * 60);
cookie.setDomain(".foo.com");
So from now on there will be only one cookie: 'foo.com' and the values will be save on the same cookie.
The problem is for old users, for them there will be two cookies ('www.foo.com' and 'foo.com'), how can i merge those two cookies to one??
One more thing, users from 'test.foo.com' eventually will visit 'www.foo.com' and vise versa.
Get the old cookie from the http servlet request, then set its max age to 0. That will trigger the client side to get rid of it (in its own time, normally right away). Also, see the Javadoc on Cookie.
setMaxAge
public void setMaxAge(int expiry)
Sets the maximum age in seconds for this Cookie.
A positive value indicates that the cookie will expire after that many seconds
have passed. Note that the value is the maximum age when the cookie will expire,
not the cookie's current age.
A negative value means that the cookie is not stored persistently and will be
deleted when the Web browser exits. A zero value causes the cookie to be deleted.
Parameters:
expiry - an integer specifying the maximum age of the cookie in seconds;
if negative, means the cookie is not stored; if zero, deletes the cookie
See Also:
getMaxAge()
You will need to parse through your cookies and search for the one you are trying to get rid of. Something like this:
final Cookie[] cookies = request.getCookies();
for(Cookie cookie: cookies) {
if("www.foo.com".equals(cookie.getDomain()) cookie.setMaxAge(0);
}
I want to add two values in cookie and retrieve them. I am doing in this way, but I am getting only the first value, not the second.
Cookie c = new Cookie("a", a);
c.setMaxAge(60);
response.addCookie(c);
Cookie b = new Cookie("d", d);
b.setMaxAge(5 * 60);
response.addCookie(b);
While reading:
Cookie cookies[] = getRequest().getCookies();
Cookie myCookie = null;
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
log.info("test ;;;"+cookies[i].getName());
}
}
This returns only one data.
You are likely reading them from the wrong request. The newly added cookies will only be available in the subsequent requests, they will not be reflected immediately in the current request. So if you for instance add a cookie to the response and then tries to read it from the current request (the one associated with the very same response where you added the cookie to), then you won't get the added cookie at all. This also applies when you're forwarding the request from one to other resource (i.e. Servlet or JSP).
Debug/read the request/response headers in the client side as well for the sake that. In FireFox you can use the Firebug for this (open the Firebug pane, go to tab Net, click the request in question and you'll see both the request/response headers, the cookies are in there as well).
I would implement something like:
for(int i= 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
log.info("name: " + cookie.getName())
log.info("value: " + cookie.getValue())
}
This should print name and values of the cookies. If this is not working, probably the cookies are not added correctly to the response. Check that the cookies length is the one expected.
You can do some thing like this dear, I have tested it and its working
response.addCookie(new Cookie("name","sunny"));
response.addCookie(new Cookie("pwd","sunnymehta"));
Cookie[] cookie=request.getCookies();
for(Cookie ck:cookie)
{
System.out.println(ck.getName());
}
I would take a look at the actual cookie being saved in your browser. The first thing that comes to mind is the fact that in the underlying file that stores your cookie data, there is actually only one file -- the cookie objects in your code are actually being encoded as name-value pairs in a single file. The article at http://www.quirksmode.org/js/cookies.html has some good detail on how the data is actually stored in the cookie file. (Actually more than name-value pairs, since it also accomodates the other cookie properties like the expiration date and the secure flag, but anyway the article will show you that format.)
I gather that your java calls should be writing a validly formatted cookie file, and generating a valid array of cookie objects for you. But the fact that you're getting one object back seems suspicious to me in light of the underlying data format of the cookie.
In the past I've used Cookie Pal to inspect raw cookie data, though the site mentions IE6 support so I guess it's a little out of date.