JavaWeb学习笔记4——Cookie永久登录案例
当用户在自家上网时,应该不难发现,在你第一次登录后,下次访问就不需要再次登录,这是因为在第一次登录时网站就记住了你的登录信息。实现这个功能其实很简单,只需要把登录信息,比如账号、密码等保存在Cookie中,并控制Cookie的有效期,下一次访问时再验证Cookie中的登录信息就可以了。
但是直接把密码保存在Cookie的做法是比较危险的,所以我们今天的案例采用了另一种方法:把账号按照一定的规则进行加密后保存到Cookie中,下次访问时只需要判断帐号的加密规则是否正确。本例把账号保存到名为account的Cookie中,把账号连同**用MD5算法加密后保存到名为ssid的Cookie中,验证时,验证Cookie中的账号与**加密后是否与Cookie中的ssid相等。
代码如下:
loginCookie.jsp
<%@ page language="java" pageEncoding="UTF-8" isErrorPage="false"%>
<%@ page import="java.security.MessageDigest" %>
<%!private static final String KEY = ":[email protected]"; //**
//md5加密算法
public final static String calcMD5(String ss) {
String s = ss == null ? "" : ss;
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
try {
byte[] strTemp = s.getBytes();
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(strTemp);
byte[] md = mdTemp.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
return null;
}
}%>
<%
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String action = request.getParameter("action");
if ("login".equals(action)) {
//获取各种参数
String account = request.getParameter("account");
String password = request.getParameter("password");
int timeout = new Integer(request.getParameter("timeout"));
String ssid = calcMD5(account + KEY);
//将账号存入accountCookie
Cookie accountCookie = new Cookie("account", account);
accountCookie.setMaxAge(timeout);
//将账号、**加密后存入accountCookie
Cookie ssidCookie = new Cookie("ssid", ssid);
ssidCookie.setMaxAge(timeout);
response.addCookie(accountCookie);
response.addCookie(ssidCookie);
//重新请求本页面
response.sendRedirect(request.getRequestURI() + "?" + System.currentTimeMillis());
return;
}
else if ("logout".equals(action)) {
Cookie accountCookie = new Cookie("account", "");
accountCookie.setMaxAge(0);//设置有效期为0,即删除
Cookie ssidCookie = new Cookie("ssid", "");
ssidCookie.setMaxAge(0);//设置有效期为0,即删除
response.addCookie(accountCookie);
response.addCookie(ssidCookie);
//重新请求本页面
response.sendRedirect(request.getRequestURI() + "?" + System.currentTimeMillis());
return;
}
boolean login = false;
String account = null;
String ssid = null;
if (request.getCookies() != null) {
for (Cookie cookie : request.getCookies()) {
if (cookie.getName().equals("account"))
account = cookie.getValue();
if (cookie.getName().equals("ssid"))
ssid = cookie.getValue();
}
}
if (account != null && ssid != null) {
login = ssid.equals(calcMD5(account + KEY));//如果加密规则正确,则login置为true,已登录
}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<legend><%=login ? "欢迎回来" : "请先登录"%></legend>
<%
if (login) {
%>
欢迎您,${cookie.account.value}.
<a href="${pageContext.request.requestURI }?action=logout"> 注销</a>
<%
} else {
%>
<form action="${pageContext.request.requestURI }?action=login" method="post">
<table>
<tr>
<td>账号:</td>
<td><input type="text" name="account" style="width:200px;"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td>有效期:</td>
<td><input type="radio" name="timeout" value=-1 checked> 关闭浏览器即失效 <br /> <input
type="radio" name="timeout" value="<%=30 * 24 * 60 * 60%>">30天内有效 <br />
<input type="radio" name="timeout" value="<%=Integer.MAX_VALUE%>">永久有效 <br /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="登录" class="button"></td>
</tr>
</table>
</form>
<%} %>
登陆时可对登录信息的有效期进行选择,这是通过设置Cookie的age属性来实现的,运行结果如图: