JavaScript Cookies使用

    Cookie 是个存储在客户端(浏览器)记录信息确定用户身份的小文本文件,可以用来跟踪用户当前登陆状态和用户浏览页面的次数,记录用户输入的文本信息,也可以在页面间传递变量,记录用户一些行为。

当浏览器运行时,存储在 RAM 中。一旦你从该网站或网络服务器退出,Cookie 也可存储在计算机的硬盘上。当访客结束其浏览器对话时,即终止的所有 Cookie。

与cookies相对应的,另一种记录客户状态的机制是session,保存在服务器端,使用起来比cookies简单。Session对应的类为javax.servlet.http.HttpSession类。Session与 Cookie一样,也是一种key-value的键值对,通过getAttribute(Stringkey)和setAttribute(String key,Objectvalue)方法读写用户状态信息。Servlet里通过request.getSession()方法获取该客户的Session。

JS设置cookies、检查cookies示例代码:

<html>
<head>
<script type="text/javascript">
function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1 
    c_end=document.cookie.indexOf(";",c_start)
    if (c_end==-1) c_end=document.cookie.length
    return unescape(document.cookie.substring(c_start,c_end))
    } 
  }
return ""
}

function setCookie(c_name,value,expiredays)
{
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}

function checkCookie()
{
username=getCookie('username')
if (username!=null && username!="")
  {alert('Welcome again '+username+'!')}
else 
  {
  username=prompt('Please enter your name:',"")
  if (username!=null && username!="")
    {
    setCookie('username',username,365)
    }
  }
}
</script>
</head>

<body onLoad="checkCookie()">
</body>
</html>
原文地址:https://www.cnblogs.com/K2154952/p/5935570.html