实现原理:
当用户已启用了自动登录时,这时我们将登录时用到的信息封装到Cookie里面,当用户下次访问时,会将cookie带过来,这时我们在Filter里面做判断
实现的步骤
在过虑器里面
1、 判断 是否已经登录(session中有登录的信息)已经登录,直接放行没有登录,进入2
2、 获得cookie并查找目标cookie
a) 没找到 没有自动登录,直接放行
b) 找到了进入3
3、 获得用户名和密码去登录
a) 失败了,直接放行
b) 登录成功,查找到的用享户存到session中再放行
<span style="white-space:pre"> </span>@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
<span style="white-space:pre"> </span>// 1.判断 是否已经登录
if(request.getSession().getAttribute("loginUser")!=null){
//说明已经登录, 就直接放行
chain.doFilter(request, response);
}else{
//说明没有 登录 ,
//获得带过来的cookie,查找目标cookie
Cookie[] cookies = request.getCookies();
Cookie targetCookie = findTargetCookie(cookies,"autologin");
if(targetCookie==null){
// 没找 到 目标 cookie , 则 直接放行
chain.doFilter(request, response);
}else{
//找到了 , 则 获得用户名和密码去登录
String username = targetCookie.getValue().split(":")[0];
String password = targetCookie.getValue().split(":")[1];
//去登录
UserService us = new UserService();
User loginUser = us.loginByUsernameAndPassword(username,password);
if(loginUser==null){
//说明 用户名或密码 被 篡改 了
// 则直接放行
chain.doFilter(request, response);
}else{
//将 user 存到 session 中去,然后 再 放行
request.getSession().setAttribute("loginUser", loginUser);
chain.doFilter(request, response);
}
}
}
}
//返回查找到的目标的cookie
private Cookie findTargetCookie(Cookie[] cookies, String name) {
if(cookies==null){
return null;
}
for (Cookie cookie : cookies) {
if(cookie.getName().equals(name)){
return cookie;
}
}
return null;
}
<span style="white-space:pre"> </span>Cookie cookie = new Cookie("autologin", loginUser.getUsername()+":"+loginUser.getPassword());
cookie.setMaxAge(60*60*24);
cookie.setPath("/");
response.addCookie(cookie);