使用过滤器实现自动登录

分析清楚逻辑结构

cookie + session + filter 技术运用

防止伪造cookie

需要改进的地方:  cookie加密技术


package com.gyarmy.demo4;

import java.io.IOException;

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 com.gyarmy.demo3.UserBean;
import com.gyarmy.demo3.UserService;

public class AutoLoginFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		
		//自动登录控制
		//1 是否登录
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)resp;
		
		//已经登录
		if(request.getSession().getAttribute("loginUser")!=null)
		{
			//自动登录
			chain.doFilter(request, response);
		}else{
			//没有登录,查看Cookie
			Cookie[] cookies = request.getCookies();
			
			Cookie targetCookie = getTargetCookie(cookies,"autologin");
			
			if(targetCookie == null)
			{
				chain.doFilter(request, response); //继续执行
			}else
			{
				//验证用户是否能登录
				System.out.println(targetCookie.getValue());
				
				//字符串截取
				String loginString = targetCookie.getValue();
				String[] strAttr = loginString.split("#gyarmy#");
				if(strAttr.length!=2)
				{
					chain.doFilter(request, response); //继续执行
				}else
				{
					UserBean autoUserLogin = new UserBean();
					autoUserLogin.setUsername(strAttr[0]);
					autoUserLogin.setPassword(strAttr[1]);
					
					//判断是否为伪造
					UserService us = new UserService();
					UserBean userLogin = us.login(autoUserLogin);
					
					if(userLogin!=null)
					{
						request.getSession().setAttribute("loginUser", userLogin);		
					}
					chain.doFilter(request, response); //继续执行
				}
			}	
		}
	}

	private Cookie getTargetCookie(Cookie[] cookies, String string) {
		// TODO Auto-generated method stub
		//获取目标cookie
		if(cookies == null)
		{
			return null;
		}
		
		for (Cookie cookie : cookies) {
			if(cookie.getName().equalsIgnoreCase("autologin"))
			{
				//找到目标cookie
				return cookie;
			}
		}
		
		
		return null;
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}


原文链接: 使用过滤器实现自动登录 版权所有,转载时请注明出处,违者必究。
注明出处格式:流沙团 ( https://gyarmy.com/post-85.html )

发表评论

0则评论给“使用过滤器实现自动登录”