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.
Related
I am building a user tracking system for a web application. People could came from many urls. I want to know from which urls the came from.
I design url like this : http://www.example.com/ref/XXXXXXX.
I create a Filter to handle incoming request :
String cookieKey = "examplesite.cookie";
String cookieValue = referralIdentifier;
Cookie cookie = new Cookie(cookieKey, cookieValue);
cookie.setMaxAge(60*60*24*365);
((HttpServletResponse) response).addCookie(cookie);
HttpServletResponse resp = (HttpServletResponse)response;
resp.addCookie(cookie);
resp.sendRedirect("/");
When this code execute, I cannot see the cookie set in the browser.
If I change the redirect to forward, I can see the cookie.
The I see this blog post how to track people with cookie and redirect where the blogger suggest to use code to redirect.
So I changed my code and I replace resp.sendRedirect("/"); by
resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
resp.setHeader("Location", "http://www.example.com/");
Here I can see the cookie in Firefox but not in Chrome.
Is there a solution to track user after redirection ?
According to http://www.javamex.com/tutorials/servlets/cookies_api.shtml by default a cookie is visible to "requests to subpaths of the parent from which the cookie was set".
This might be your problem. To make the cookie visible on all paths, you can set the path to "/" using cookie.setPath("/").
I'm having an issue with deleting cookies from my servlet code. Given bellow is my code.
private void clearCookies(HttpServletRequest req, HttpServletResponse resp) {
Cookie[] cookies = req.getCookies();
for (Cookie curCookie : cookies) {
curCookie.setValue(null);
curCookie.setMaxAge(0);
curCookie.setPath("/");
resp.addCookie(curCookie);
}
}
I do a resp.sendRedirect(url) after this method call. However, not all cookies get deleted, for example this cookie never get deleted.
Name: reqURI
Content: ../../webapp/index.jsp
Domain: mgt.appserver.com
Path: /
Send for: Any kind of connection
Accessible to script: Yes
Created: Tuesday, November 26, 2013 4:35:19 PM
Expires: When the browsing session ends
Does anyone knows what I'm missing here? I read the Java Cookie object documentation and according to that value 0 should make the cookie to be removed. But it's not. And I tried many more suggestions and none of it worked. I tried this with Google Chrome and Firefox, so can't believe it's an issue with the browsers. I have no idea why such a generic thing is not properly documented and complected in a language like Java.
Update
As per Problem removing cookie in servlet
The path and domain will always be null when you retrieve cookies in Java because they are only necessary in the response for the client browser. However, if you're in the same security domain (regardless of the path), you still have the rights to delete them. Unfortunately, because the path is not included you can't delete the cookie now without explicitly knowing that path. Simply using the same cookie name, but a different path will not work. Those are considered two different cookies, and you will find that instead of deleting the cookie, you just created another one on a different path.
So you should not change value or path as this will create a new cookie
Where are you redirecting? The response has to be committed back to the host that created the cookie in the first place in order for it to be removed. Also, you don't need to set the value to null.
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.
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.
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.