1.Cookies是存储在客户机的文本文件,会将用户的个人信息保存在客户端 2.从安全角度来说,使用 cookie 存在着一定的风险,因此不建议在 cookie 中保存比较重要或隐私的内容
| 方法 | 说明 |
|---|---|
| 设置 | |
| public void setValue(String newValue) | 设置 cookie 的值 |
| public void setMaxAge(int expiry) | 设置 cookie 有效期,单位:秒 默认仅在当前会话中存在 |
| public void setDomain(String pattern) | 设置 cookie 的域名,如 biancheng.net |
| public void setPath(String uri) | 设置 cookie 的路径 默认为当前页面目录以及子目录下的所有 URL |
| public void setSecure(boolean flag) | 设置 cookie 是否要加密传输 |
| public void setComment(String purpose) | 设置 cookie 注释 |
| 获取 | |
| public String getValue() | 获取 cookie 的值 |
| public String getDomain() | 获取 cookie 的域名 |
| public int getMaxAge() | 获取 cookie 有效期,单位:秒 默认为 -1,表示 cookie 保存到浏览器关闭为止 |
| public String getPath() | 获取 cookie 的路径 |
| 返回 | |
| public String getName() | 返回 cookie 的名称,名称创建后将不能被修改 |
| public String getComment() | 返回 cookie 注释,如果 cookie 没有注释,则返回 null |
注意:name 和 value 中不能包含空格和以下字符:[ ] ( ) = , " / ? @ : ;
示例
解决中文乱码: String str = URLEncoder.encode(request.getParameter("name"), "utf-8");//编码 String str = URLDecoder.decode(str, "utf-8");//解码 写入: cookie ck = new cookie(String name,String value);//创建 cookie 对象 ck.setMaxAge(60*60*24);//设置 cookie 有效期24小时 response.addcookie(ck);//在响应头部添加cookie 读取: cookie cookie = null; //创建cookie对象
cookie[] cookies = null;
cookies = request.getcookies();// 获取 cookie 的数据
if (cookies != null) {//判断是否为空
for (int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
out.print("参数名 : " + cookie.getName());
out.print("参数值: " + URLDecoder.decode(cookie.getValue(), "utf-8") + " <br>"); }
} 删除: cookie cookie = null; //创建cookie对象
cookie[] cookies = null;
cookies = request.getcookies();// 获取 cookie 的数据
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
if ((cookie.getName()).compareTo("name") == 0) { //删除参数名为name的cookie
cookie.setMaxAge(0);//将有效时间设0,立刻过期
response.addcookie(cookie);
}
}
}