欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用cookie和session实现自动登录 博客分类: JAVA EE javafilterservlet 

程序员文章站 2024-03-21 21:52:04
...
算是今天的学习笔记吧。。。
在点击登录输入用户名和密码后,当验证用户名和密码都正确且有正确返回值时,在LoginSvl中创建一个cookie保存此用户名和密码:
String unamepwd = user.getUname()+","+user.getPwd();
Cookie cookie=new Cookie("unamepwd",unamepwd);
cookie.setMaxAge(60*60*24*7);
response.addCookie(cookie);

创建一个过滤器,在下次登录时,当session中的user为空,则从cookie中获取上次保存的用户名密码,调用biz,通过biz调dao,验证cookie中保存的信息是否是否适用于此次登录,即验证数据库中密码或用户名是否改变,若改变,则清除此cookie。若没改变,则自动登录。
LoginFilter中的代码:
    public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest request=(HttpServletRequest) req;
		HttpServletResponse response=(HttpServletResponse) resp;
		if(request.getSession().getAttribute("user") == null){
			Cookie loginCookie=getLoginCookie(request, "unamepwd");
			if(loginCookie != null){
				String[] unamepwds=loginCookie.getValue().split(",");
				UserBiz bbiz =new UserBiz();
				User uuser=bbiz.login(unamepwds[0], unamepwds[1]);
				if(uuser != null){
					request.getSession().setAttribute("user", uuser);
				}else{
					Cookie cookie=new Cookie(loginCookie.getName(),null);
					cookie.setMaxAge(0);
					response.addCookie(cookie);
				}
			}
			
		}
		chain.doFilter(request, response);
	}
	
	private Cookie getLoginCookie(HttpServletRequest request,String cookieName){
		Cookie strRet = null;
		if(request.getCookies() != null){
			Cookie[] cookies = request.getCookies();                             
			for(int i=0;i<cookies.length;i++){
				Cookie cookie = cookies[i];
				String cm = cookie.getName();			
				if(cm.equals(cookieName)){	
					strRet = cookie;	
					break;
				}				
			}
		}
		return strRet;
	}

注:filter需要在web.xml中做响应配置。其中<url-pattern></url-pattern>中只能写/*,否则不能自动登录。
最后要在点击退出按钮时,清除cookie,以免其他用户无法登录:
LoginOutSvl中代码:
public void service(HttpServletRequest request,HttpServletResponse response)
    throws ServletException,IOException{
		
		request.getSession().invalidate();
		Cookie loginCookie = getLoginCookie(request, "unamepwd"); 
		Cookie cookie=new Cookie(loginCookie.getName(),null);
		cookie.setMaxAge(0);   
		response.addCookie(cookie);
		request.getRequestDispatcher("MainSvl").forward(request,response);
	
	}
	
	private Cookie getLoginCookie(HttpServletRequest request,String cookieName){
		Cookie strRet = null;
		if(request.getCookies() != null){
			Cookie[] cookies = request.getCookies();                             
			for(int i=0;i<cookies.length;i++){
				Cookie cookie = cookies[i];
				String cm = cookie.getName();			
				if(cm.equals(cookieName)){	
					strRet = cookie;	
					break;
				}				
			}
		}
		
		return strRet;
	}