使用cookie实现永久登陆
1,在cookie里面保存账号密码然后和数据库核对(由于我没有使用数据库,就不用了
2,在cookie里面保存时间戳和账号使用加密解密(我也没有使用时间戳
思路,request.getParameter("account");,获得账号,存入cookie,加入时间戳重定制网页内容
由于重定制的关系,这个时候我们不能用getParameter了,只能在cookie获得资料
原码
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%!private static final String KEY = "huanggabin"; public final static String getPassword(String a) {
return a;
}%>
<%
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String action = request.getParameter("action");
if ("login".equals(action)) {
String account = request.getParameter("account");
String account2 = request.getParameter("account");
System.out.println(account2);
String password = request.getParameter("password");
int timeout = Integer.parseInt(request.getParameter("timeout"));
String ssid = getPassword(account + KEY);
Cookie accountCookie = new Cookie("account", account);
accountCookie.setMaxAge(timeout);
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);
Cookie ssidCookie = new Cookie("ssid", "");
ssidCookie.setMaxAge(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(getPassword(account + KEY));
}
%>
<%
String account2 = request.getParameter("account");
//System.out.println(account2);
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script>
alert(document.cookie);
</script>
</head>
<body> <%=login ? "欢迎回来" : "请先登录"%><br />
<%
if (login) {
%>
欢迎你!!!,<%=account%>
<a href="${pageContext.request.requestURI}?action=logout">注销</a>
<%
} else {
%>
<form action="${pageContext.request.requestURI}?action=login"
method='post'>
账号:<input type="text" name="account"><br /> 密码: <input
type="text" name="password"><br /> 有效期: <input type="radio"
name="timeout" value="-1">关闭浏览器失效<br /> <input type="radio"
name="timeout" value="<%=30 * 24 * 60 * 60%>">30天有效<br /> <input
type="radio" name="timeout" value="<%=Integer.MAX_VALUE%>">永久有效<br />
<input type="submit" value="登陆 " class="button">
</form>
<%
}
%>
</body>
</html>