2.5. Cookie的生存时间
★默认情况下,浏览器会将Cookie保存在内存中,只要浏览器不关闭,Cookie一直存在
★如果希望关闭浏览器之后Cookie仍存在,可以通过设置Cookie过期时间
★void c.setMaxAge(int seconds);//单位是秒
seconds>0:Cookie保存在硬盘上,如果超过这个时间,浏览器会删除这个Cookie
seconds=0:删除Cookie,在修改Cookie的生存时间为0后,随着response发送回客户端,替换原有Cookie,因生命周期到了即将该Cookie删除
seconds<0:缺省值,浏览器会将Cookie保存在内存中
2.6. Cookie编码和解码
★Cookie只能保存合法的ASCII字符,如果要保存中文,需将中文转换成合法的ASCII字符,即编码
Cookie c = new Cookie("city",URLEncoder.encode("北京","utf-8"));
★编码过后的Cookie需要经过解码才能识别
String value = c.getValue();
value = URLDecoder.decode(value,"utf-8"));
*************************************jsp*************************
<%
String name = null;
String pwd = null;
Cookie[] cookies = request.getCookies();
if(cookies != null) {
for(Cookie cookie:cookies){
if("name".equals(cookie.getName())){
name = cookie.getValue();
name = URLDecoder.decode(name,'utf-8');
}
if("pwd".equals(cookie.getName())){
pwd = cookie.getValue();
}
}
request.setAttribute("name", name);
request.setAttribute("pwd", pwd);
}
%>
<form action="login" method="post">
姓名:<input type="text" name="name" value="${name}"/><br/>
密码:<input type="password" name="pwd" value="${pwd}"/><br/>
<label>
<input type="checkbox" name="week" value="7"/>一周内自动登录
</label><br/>
<input type="submit" value="login"/>
</form>
************************************ servlet的方法里面***********************************
String name = req.getParameter("name");
String pwd = req.getParameter("pwd");
String week = req.getParameter("week");
if(week != null){
name = URLEncoder.encode(name,'utf-8');
Cookie username = new Cookie("name", name);
Cookie password = new Cookie("pwd", pwd);
username.setMaxAge(7*24*3600);
password.setMaxAge(7*24*3600);
resp.addCookie(username);
resp.addCookie(password);
req.getRequestDispatcher("ok.jsp").forward(req, resp);
}