您的位置:首页 > Web前端 > JavaScript

使用javascript及java对Cookie的读写

2007-08-13 16:14 471 查看
1、javascript读取cookie
操作步骤:
1):取得当前网站的所有COOKIE,确定长度是否大于0。
2):如果大于0,再看要查找的COOKIE名是否在取得的字符串中。
3):如果在,取得该(COOKIE名+其长度+等号)对应的位置,作为起始位置;
4):从该起始位置,找到第一们“;”所在的位置。
5):取中间的内容,就是需要的COOKIE值。
//读取Cookie的函数
function readCookie(name)
{
var cookieValue = "";
var search = name + "=";
if(document.cookie.length > 0)
{
offset = document.cookie.indexOf(search);
if (offset != -1)
{
offset += search.length;
end = document.cookie.indexOf(";",offset);
if (end == -1) end = document.cookie.length;
cookieValue = unescape(document.cookie.substring(offset, end))
}
}
return cookieValue;
}

//这个很简单,直接使用document.cookie等于(COOKIE名等于对应的值)就OK
//写入Cookie的函数
function writeCookie(name, value, hours)
{
var expire = "";
if(hours != null)
{
expire = new Date((new Date()).getTime() + hours * 3600000);
expire = "; expires=" + expire.toGMTString();
}
document.cookie = name + "=" + escape(value) + expire;
return cookieValue;
}
2、Java读取COOKIE
首先要通过Cookie[] cookies=request.getCookies();取得所有的COOKIE,然后使用下面的函数取得需要的COOKIE值,没有就返回null
//取得COOKIE
public String getCookieValue(Cookie[] cookies, String cookieName) {
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName())) {
return (cookie.getValue());
}
}
return null;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: