how to add data in cookie - java

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.

Related

Strip quotes from Cookie value [duplicate]

I need to create cookie with e-mail address as value - but when I try to - then I have result:
"someone#example.com"
but I would like to have:
someone#example.com
The cookie should be created without double quoted marks - because other application uses it in such format. How to force java to not to add double quoted? Java adds them because there is special char "at".
I create the cookie that way:
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
Cookie cookie = new Cookie("login", "someone#example.com");
cookie.setMaxAge(2592000);
cookie.setDomain("domain.com");
cookie.setVersion(1);
response.addCookie(cookie);
Thanks for any help.
It's indeed caused by the # sign. This is not allowed in version 0 cookies. The container will implicitly force it to become a version 1 cookie (which breaks in MSIE browsers). You'd like to URL-encode the cookie value on cookie's creation
Cookie cookie = new Cookie("login", URLEncoder.encode("someone#example.com", "UTF-8"));
cookie.setMaxAge(2592000);
cookie.setDomain("domain.com");
response.addCookie(cookie);
and URL-decode it on cookie reading
String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
Note that you should for sure not explicitly set the cookie version to 1.
See also:
Why do cookie values with whitespace arrive at the client side with quotes?
Unrelated to the concrete problem, cookies are visible and manipulatable by the enduser or man-in-the-middle. Carrying the email address around in a cookie is a bad smell. What if the enduser changes it to a different address? Whatever functional requirement (remembering the login?) you thought to solve with carrying the email address around in a cookie should most likely be solved differently.
See also:
How do I keep a user logged into my site for months?

In Java servlet, cookie.getMaxAge() always returns -1

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.

How to delete Cookies from different path?

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.

Get Cookie in Java

I want to get the cookie value sent from a web browser from a Java application.
The cookie is not sent in response headers from the WebServer. I think the cookie is being sent as a Session cookie - which I am not able to get the cookie value in Java application.
I tried this:
CookieHandler handler = CookieHandler.getDefault();
if (handler != null) {
Map<String, List<String>> headers = handler.get(url.toURI(), new HashMap<String, List<String>>());
List<String> values = headers.get("Cookie");
for (Iterator<String> iter=values.iterator(); iter.hasNext();) {
String v = iter.next();
if (cookieValue == null)
cookieValue = v;
else
cookieValue = cookieValue + ";" + v;
}
}
but my efforts in vain, I am not able to get the cookie. I tried simply typing the URL in the browser, and I am able to see the 'Cookie' in the browser, but I am not able to get the same cookie from the java program - any help could be greatly helpful
Thanks BalusC, I will explain the issue.
I was actually looking out for a Cookie from Google Analytics and the Cookie is of the form "__gads:ID=blah".
This Cookie is sent to the Client only for the first time and if it already exists - Google Analytics wont send the Cookie again (all these days I am Checking for this Cookie)
Now my question where can I find this Cookie, which should be already existing in my system. Any thoughts?
This won't work. The java.net.CookieHandler is completely unrelated to the webbrowser-specific cookie stores. The CookieHandler is only been used when java.net.URLConnection is been used to programmatically fire HTTP requests using Java language (see also this mini tutorial)
If you intend to access a webbrowser-specific cookie store, then you'd have to use their Java API -if any provided by the particular webbrowser make-, or to look/guess their location at the disk file system and/or in the platform-specific registry, depending on the webbrowser make/version and the platform used.

Update domain of existing cookie

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.

Categories