一、基本概念
1.Cookie 是存储在客户端计算机上的文本文件,并保留了各种跟踪信息。cookie是由HTTP协议制定的,Java Servlet 显然支持 HTTP Cookie。
2.cookie是由服务器创建并保存到浏览器的一个键值对,用于跟踪用户状态,Cookie 通常设置在 HTTP 头信息中。
3.HTTP协议规定通常情况一个cookie最大4kb,一个服务器最多向一个浏览器保存20个cookie,一个浏览器最多可以保存300个cookie
二、常用方法
1.构造方法Cookie("key","value"),创建一个 Cookie 对象,如Cookie cookie1 = new Cookie("userName","ZhangSan");
2.response.addCookie(),发送 Cookie 到 HTTP 响应头,并保存到浏览器。其原始方法为response.addHeader("Set-Cookie","userName=ZhangSan")。
3. request.getCookies(),获取浏览器归还的cookie。
4.cookie1.getName(),该方法返回 cookie 的名称。名称在创建后不能改变。
5.cookie1.getValue(),该方法获取与 cookie 关联的值。setValue(String newValue)设置与 cookie 关联的值。
6.cookie1.setMaxAge(int maxAge),该方法设置 cookie 过期的时间(以秒为单位)。如果不这样设置,cookie 只会在当前 session 会话中有效。
注意:maxAge>0,浏览器会把cookie保存到客户机硬盘上,有效时长为maxAge秒。
maxAge<0(默认),cookie只存在于浏览器内存中,当用户关闭浏览器时,浏览器进程结束,同时清除这个cookie。
maxAge=0,cookie1.setMaxAge(0),浏览器会马上删除cookie1。
7.cookie1.setPath(String uri),该方法设置 cookie 的path值。path的默认值为设置页面的上级目录,如在/testweb/cookie/a.jsp中设置cookie1,则cookie1的默认path值为/testweb/cookie
注意:
- path是cookie的一个属性,由服务器创建cookie时设置,并不是cookie在客户机的保存路径。当浏览器访问服务器时,只有访问路径包含cookie1的path值,浏览器才会归还cookie1。
- 当初次请求时,服务器必定创建cookie("JSESSIONID","**32位16进制字符串ID**"),path=/项目名,无论是否创建其他cookie。
8.cookie1.setDomain(String pattern),该方法设置 cookie 适用的域。
例如 ,当www.baidu.com,www.zhidao.baidu.com,www.news.baidu.com之间共享cookie1时,可以设置domain,
step1:cookie1.setDomain(".baidu.com");
step2:cookie1.setPath("/");
三、示范
保存cookie
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>a.jsp</h1>
<h1>保存cookie</h1>
<%
Cookie cookie1 = new Cookie("aaa","AAA");
response.addCookie(cookie1);
Cookie cookie2 = new Cookie("bbb","BBB");
response.addCookie(cookie2);
%>
</body>
</html>
获取cookie
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>b.jsp</h1>
<h1>获取cookie</h1>
<%
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie c : cookies){
out.println(c.getName()+":"+c.getValue()+"<br/>");
}
}
%>
</body>
</html>