使用javascript及java对Cookie的读写

分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

                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;
    }
            

分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自blog.csdn.net/fdyufgf/article/details/87911853