setMaxAge(intexpiry)方法来设置Cookie的有效期。参数expiry以秒为单位,它具有以下含义:
·如果expiry大于零,就指示浏览器在客户端硬盘上保存Cookie的时间为expriy秒。
·如果expiry等于零,就指示浏览器删除当前Cookie。
·如果expiry小于零,就指示浏览器不要把Cookie保存到客户端硬盘。Cookie仅仅存在于当前浏览器进程中,当浏览器进程关闭,Cookie也就消失。
1.登录界面:
<%
//先读取本地是否保存用户名和密码
String account = "";
String pw = "";
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("account")) {
account = cookie.getValue();
}
if (cookie.getName().equals("password")) {
pw = cookie.getValue();
}
}
}
System.out.print(account);
System.out.print(pw);
%>
<form action="login" method="post">
<img src="./img/loginpage/loginpage.png">
<table align="center" cellpadding="0" cellspacing="0">
<tr>
<td>用户名:</td>
<td><input type="text" name="account" value="<%=account %>"
width=200> <a href="register.jsp">注册账号</a></td>
</tr>
<tr>
<td><br /></td>
</tr>
<tr>
<td>密 码:</td>
<td><input type="password" name="password" value="<%=pw %>"
width=200 /> </td>
</tr>
</table>
<br />
<div align="center">
<input type="checkbox" name="rememb" checked="checked" value="yes" />记住密码 <br />
<input type="submit" value="登录" />
</div>
</form>
2.servlet端
String name = request.getParameter("account");
String pw = request.getParameter("password");
String rememb = request.getParameter("rememb");
System.out.println(name);
System.out.println(pw);
System.out.println(rememb);
User u = Login.login(name, pw);
if (u.getRights() >= 0) {
Cookie cookie1 = new Cookie("account", u.getAccount());// 建立cookie
Cookie cookie2 = new Cookie("password", u.getPassword());// 建立cookie
if (rememb!=null) {
// 将用户登录的信息保存到本地cookie中,保存一周。
cookie1.setMaxAge(7 * 24 * 60 * 60);
cookie2.setMaxAge(7 * 24 * 60 * 60);
}else {
//不记住密码时,将本地的记录清除;
cookie1.setMaxAge(0);
cookie2.setMaxAge(0);
}
response.addCookie(cookie1);// 写入本地
response.addCookie(cookie2);// 写入本地