学会使用浏览器缓存cookie
生活中的cookie:
系统会记录已经浏览过的搜索记录
- cookie是Web服务器保存在客户端的一系列文本信息
- cook的作用:
- 对特定的对象追踪
- 实现各种个性化功能
- 简化登录
- 安全性能:
- 容易泄露信息
在JSP中使用cookie:
语法:
Cookie newCookie =new Cookie(String key,String value);
response.addCookie(newCookie);
Cookie[ ] cookies = request.getCookies();
TestCookie.jsp:
<%
String username="curry";
String password="30";
Cookie uesernameCookie=new Cookie("username",username);
Cookie passwordCookie=new Cookie("password",password);
response.addCookie(uesernameCookie);
response.addCookie(passwordCookie);
%>
showCookie:
<%
Cookie cookies[] = request.getCookies();
for (Cookie cookie : cookies) {
String key= cookie.getName();
if (key.equals("username")){
out.println("username:"+cookie.getValue());
}
if (key.equals("password")){
out.println("password:"+cookie.getValue());
}
}
%>
showSessionId:
<%
out.print(session.getId());
Cookie cookies[]= request.getCookies();
for (Cookie cookie : cookies) {
out.println("key:"+cookie.getName());
out.println("value:"+cookie.getValue());
out.println("<br>");
}
%>
Cookie对象的常用方法:
Cookie对象的常用方法:
方法名称 |
说明 |
void setMaxAge(int expiry) |
设置cookie的有效期,以秒为单位 |
void setValue(String value) |
在cookie创建后,对cookie进行赋值 |
String getName() |
获取cookie名称 |
String getValue() |
获取cookie的值 |
int getMaxAge |
获取cookie的有效时间,以秒为单位 |
小结:
cookie与session的对比:
Cookie代码实现 以及显示返回登录时间,可查看文章:http://t.csdn.cn/dBh51