cookie的使用

cookie的使用

一.什么是cookie?

cookie 是存储于访问者的计算机中的变量。每当同一台计算机通过浏览器请求某个页面时,就会发送这个 cookie。你可以使用 JavaScript 来创建和取回 cookie 的值。

有关cookie的例子:

名字 cookie
当访问者首次访问页面时,他或她也许会填写他/她们的名字。名字会存储于 cookie 中。当访问者再次访问网站时,他们会收到类似 "Welcome John Doe!" 的欢迎词。而名字则是从 cookie 中取回的。
密码 cookie
当访问者首次访问页面时,他或她也许会填写他/她们的密码。密码也可被存储于 cookie 中。当他们再次访问网站时,密码就会从 cookie 中取回。
日期 cookie
当访问者首次访问你的网站时,当前的日期可存储于 cookie 中。当他们再次访问网站时,他们会收到类似这样的一条消息:"Your last visit was on Tuesday August 11, 2005!"。日期也是从 cookie 中取回的。

 

二.实验项目

代码 login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>登录页面</title>
<%
String username = "";
String password = "";
//获得当前站点所有的Cookie
Cookie[] cookies = request.getCookies();
for(int i=0; i<cookies.length;i++){
    //对cookies中的数据进行遍历,找到用户名密码的数据
    if("username".equals(cookies[i].getName())){
        username = cookies[i].getValue();
    }else if("password".equals(cookies[i].getName())){
        password = cookies[i].getValue();
    }
}
%>
</head>
<body>
<form action="LoginServlet" method="post">
username:<input type="text" name="name" value="<%=username%>"/><br/>
password:<input type="password" name="pwd" value="<%=password%>"/><br/>
<input type="checkbox" value="y" name="isLogin">自动登录<br/>
<input type="submit" value="登录"/>
</form>
</body>
</html>

创建存储cookie

<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://pan.baidu.com/s/1Bd3PKExC56mneN_ekzozTA 
提取码:gtyo

 

posted @ 2019-04-04 14:26  六月七日·k  阅读(161)  评论(0)    收藏  举报