一、Servlet
package autologin.servlet.login;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.tomcat.util.codec.binary.Base64;
import autologin.domain.Admin;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String oper=request.getParameter("oper");
if("pre".equals(oper)){
Cookie autoLoginCookie = getCookie(request);
if(autoLoginCookie!=null){
String value=autoLoginCookie.getValue();
if(!"".equals(value)){
String[] values=value.split(":");
if(values.length==2){
request.setAttribute("auto", 0);
request.setAttribute("name", values[0]);
request.setAttribute("pass", values[1]);
}else if(values.length==3){
request.setAttribute("name", values[0]);
request.setAttribute("pass", values[1]);
request.setAttribute("auto", values[2]);
}
}
}
request.getRequestDispatcher("./login.jsp").forward(request, response);
}else if("login".equals(oper)){
String name=request.getParameter("name");
String pass=request.getParameter("pass");
String[] rpass=request.getParameterValues("rpass");
String[] alogin=request.getParameterValues("alogin");
if("zsf".equals(name)&&"123".equals(pass)){
Admin admin=new Admin(name, pass);
//存储到session中去
request.getSession().setAttribute("admin", admin);
loginCookie(request, response, name, pass, rpass, alogin);
request.getRequestDispatcher("./index.jsp").forward(request, response);
}else{
loginCookie(request, response, name, pass, rpass, alogin);
//登录失败,重定向
response.sendRedirect("./login.do?oper=pre");
}
}else if("delete".equals(oper)){
HttpSession session=request.getSession();
session.removeAttribute("admin");
request.getRequestDispatcher("./index.jsp").forward(request, response);
}
}
private Cookie getCookie(HttpServletRequest request) {
Cookie[] cookies=request.getCookies();
Cookie autoLoginCookie=null;
if(cookies!=null&&cookies.length>0){
for(Cookie cookie:cookies){
String cookieName=cookie.getName();
if("autologin".equals(cookieName)){
autoLoginCookie=cookie;
}
}
}
return autoLoginCookie;
}
private void loginCookie(HttpServletRequest request,
HttpServletResponse response, String name, String pass,
String[] rpass, String[] alogin) {
String value="";
if(alogin!=null){
//自动登录操作
value=name+":"+md5(pass)+":"+1;
}else if(rpass!=null){
//记住密码操作
value=name+":"+md5(pass);
}
Cookie autoLoginCookie = getCookie(request);
if(autoLoginCookie==null){
autoLoginCookie=new Cookie("autologin", value);
}else{
//重新设置值
autoLoginCookie.setValue(value);
}
//加入到响应中
response.addCookie(autoLoginCookie);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
public String md5(String input){
try {
MessageDigest md=MessageDigest.getInstance("md5");
byte buffer[]=md.digest(input.getBytes());
byte[] temp=Base64.encodeBase64(buffer);
System.out.println(new String(temp));
return new String(temp);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
二、Filter
package autologin.filter;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.tomcat.util.codec.binary.Base64;
import autologin.domain.Admin;
public class AutoLoginFilter implements Filter{
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest) req;
HttpServletResponse response=(HttpServletResponse) res;
String oper=request.getParameter("oper");
//判断是否是登录的准备操作,如果不是直接放行
if(!"pre".equals(oper)){
chain.doFilter(request, response);
return;
}
//1.获取session中的用户,如果有就不需要登录,如果没有直接放行
HttpSession session=request.getSession();
Admin admin=(Admin)session.getAttribute("admin");
if(admin!=null){
request.getRequestDispatcher("./index.jsp").forward(request, response);
return;
}
//2.获取Cookie中的auto标志对象,对象为空,则继续执行
Cookie autoLoginCookie=getCookie(request, "autologin");
if(autoLoginCookie==null){
chain.doFilter(request, response);
return;
}
//3.autologin name:pass:auto拆分autologin标志,返回长度如果为2,否则继续 执行
String value=autoLoginCookie.getValue();
if(value==null||"".equals(value)){
chain.doFilter(request, response);
return;
}
//4.autologin的长度等于3证明是自动登录操作
String[] values=value.split(":");
if(values!=null&&values.length==2){
chain.doFilter(request, response);
return;
}
if(values.length==3){
String name=values[0];
String pass=values[1];
//5.根据name查找这个用户的密码,pass findById Admin getObjectByName(String name)
Admin getAdmin=new Admin("zsf","123");
//根据用户名称查询得到的密码
String gpass=getAdmin.getPass();
//6判断查询出的pass与autologin标志的pass是否一样,如果不一样,就登录界面
if(md5(gpass).equals(pass)){
//7.如果一样,证明有这个用户,自动登录成功,存储到session中
session.setAttribute("admin", getAdmin);
request.getRequestDispatcher("./index.jsp").forward(request, response);
return;
}
}
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
private Cookie getCookie(HttpServletRequest request,String name) {
Cookie[] cookies=request.getCookies();
Cookie autoLoginCookie=null;
if(cookies!=null&&cookies.length>0){
for(Cookie cookie:cookies){
String cookieName=cookie.getName();
if(name.equals(cookieName)){
autoLoginCookie=cookie;
}
}
}
return autoLoginCookie;
}
//md5加密
public String md5(String input){
try {
//消息摘要加密类对象
MessageDigest md=MessageDigest.getInstance("md5");
//加密算法
byte buffer[]=md.digest(input.getBytes());
//安装base64进一步处理
byte[] temp=Base64.encodeBase64(buffer);
System.out.println(new String(temp));
return new String(temp);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
三、页面
(1)index.jsp
<body>
<div>
<h1>首页</h1>
</div>
<c:if test="${admin!=null }">
<div>
欢迎${admin.name }登录
<a href="${pageContext.request.contextPath }/login.do?oper=delete">注销</a>
</div>
</c:if>
<c:if test="${admin==null }">
<div>
<a href="${pageContext.request.contextPath }/login.do?oper=pre">登录</a>
</div>
</c:if>
</body>
(2)login.jsp
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript">
window.οnlοad=function(){
var aloginDom=document.getElementById("alogin");
var rpassDom=document.getElementById("rpass");
//自动登录事件
aloginDom.οnclick=function(){
if(this.checked){ //判断自己是否为真
if(!rpassDom.checked){//记住密码是否为真,如果为假就让它设置为真
rpassDom.checked=true;
}
}
};
//记住密码事件
rpassDom.οnclick=function(){
if(aloginDom.checked){//首先判断自动登录是否为真
this.checked=true;//它永远为真
}
};
};
</script>
</head>
<body>
<div style="text-align: center;">
<h3>用户登录</h3>
<div style="text-align: center;">
<form action="${pageContext.request.contextPath }/login.do?oper=login" method="post">
<table cellpadding="0" cellspacing="0" border="1">
<tr>
<td>用户名</td>
<td><input type="text" name="name" value="${name }" /></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" name="pass" value="${pass}"/></td>
</tr>
<tr>
<td colspan="2">
<c:if test="${auto==null }">
<input type="checkbox" name="rpass" id="rpass"/>记住密码
<input type="checkbox" name="alogin" id="alogin"/>自动登录
</c:if>
<c:if test="${auto==0 }">
<input type="checkbox" name="rpass" id="rpass" checked="checked"/>记住密码
<input type="checkbox" name="alogin" id="alogin"/>自动登录
</c:if>
<c:if test="${auto==1 }">
<input type="checkbox" name="rpass" id="rpass" checked="checked"/>记住密码
<input type="checkbox" name="alogin" id="alogin" checked="checked"/>自动登录
</c:if>
</td>
</tr>
<tr>
<td colspan="2">
<table width="100%"><tr>
<td align="center"><input type="submit" name="submit" value="登录"/></td>
<td align="center"><input type="reset" name="reset" value="重置"/></td>
</tr></table>
</td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
四、web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>autologin</display-name>
<filter>
<filter-name>AutoLoginFilter</filter-name>
<filter-class>autologin.filter.AutoLoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AutoLoginFilter</filter-name>
<url-pattern>/login.do</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>autologin.servlet.login.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>