1. 简介
Cookie对象是由服务器产生并保存到客户端(内存或者文件中)的信息,用来记录用户个人信息以及个性化设置,用户每次访问站点是,web应用程序都可以读取Cookie包括的信息,
2. Cookie基本用法
2.1 向客户程序发送Cookie
1.创建Cookie对象
Cookie c=new Cookie(“username”,“123456”);
分别是Cookie的名称和Cookie的值。
2.设置最大时效,单位是秒s
c.setMaxAge(60);一分钟
3.将Cookie放入HTTP响应中,使用response.addCookie,
格式为:response.addCookie©;
2.2从客服端读取Cookie
1.调用request.getCookie,创建并得到Cookie对象组成的数组。
2.在Cookie对象数组中,利用循环调用每个对象的getName。
3.获得响应的value
getValue
如果要删除某个Cookie对象的时候,把它的最大时效设为0;
3.利用Cookie实现自动登录
Input.jsp
<%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head><title>用户登录页面!</title></head>
<body>
<form action="Show.jsp" method="post">
用户名:<input type="text" name="username"/><br/>
密码:      <input type="password" name="userpd"><br/>
<input type="submit" value="登 录">
</form>
</body>
</html>
登录处理页面
Show.jsp
<%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head><title>登录处理页面!</title></head>
<body>
<%
String name=request.getParameter("username");
if(name!=null)
{
Cookie c=new Cookie("username",name);
c.setMaxAge(300);
//将cookie数组保存到客户端
response.addCookie(c);
session.setAttribute("username", name);
response.sendRedirect("main.jsp");
}
%>
</body>
</html>
main.jsp
<%@page language="java" pageEncoding="UTF-8" contentType="text/html"%>
<html>
<head><title>主页面</title></head>
<body>
<%
String username=(String)session.getAttribute("username");
if(username==null)
{
Cookie []Co=request.getCookies();
String judge=null;
if(Co!=null)
{
for(int i=0;i<Co.length;i++)
{
if(Co[i].getName().equals("username"))
{
judge=Co[i].getValue();
}
/*
if(Co[i].getValue().equals(username))
judge=username;
*/
}
}
if(judge!=null)
{
session.setAttribute("username", judge);
out.print("您好!"+username);
}
else
{
out.print("您还没注册呢! 三秒后跳转到注册页面!");
response.setHeader("Refresh","3;url=Input.jsp");
}
}
else
{
//session中用户名不空说明用户已经登录了
out.print("您好!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"+username);
}
%>
</body>
</html>