Filter 实现自动登录

实现原理:

当用户已启用了自动登录时,这时我们将登录时用到的信息封装到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;
	}


回写Cookie:

<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);



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值