I am setting cookie server-side, using java code
response.addCookie("test1","test1");
I found this code to retrieve cookie using javascript
(function(){
var cookies;
function readCookie(name,c,C,i){
if(cookies){ alert("all cookies"+cookies); return cookies[name]; }
c = document.cookie.split('; ');
cookies = {};
for(i=c.length-1; i>=0; i--){
C = c[i].split('=');
cookies[C[0]] = C[1];
}
alert("required cookie"+cookies[name]);
return cookies[name];
}
window.readCookie = readCookie; // or expose it however you want
})();
I am calling this function as
alert(readCookie('test1'));
but every time I get the alert as undefined.. I checked the chrome's cookie file and my cookie is set there as
localhosttest1test1/service/login
Can someone explain why am I getting this error?
The code seems to work (I tested it in Firefox, Chrome and MSIE, by creating some cookie with JavaScript, eg, document.cookie = "test1=bla"
, and it displays "required cookiebla"). Maybe the cookie you set from the server is marked as HttpOnly
, so that JavaScript has no access to it?
I had a similar problem when I submitted a link that went to a different path. ie, the page I was clicking the link was /pathOne/somePlace
, but the link went to /pathTwo/someOtherPlace
. The cookie that was written was only valid on /pathTwo/*
. To correct for this I did :
Cookie testCookie = new Cookie("test1","test1");
testCookie.setPath (request.getContextPath ());
response.addCookie (testCookie);
hope that helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.