使用Cookie实现自动登录

#说明
      在之前的博文《了解Cookie和Session》中,我们初步认识了Cookie和Session。在之后的学习中,了解了Cookie的使用场景:A. sessionid的存储 B.购物车 C.自动登录。本文对使用Cookie实现自动登录的原理和代码实现进行阐述。

#正文
##实现原理
Cookie如何保存信息?
      A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.(摘自Servlet文档)

cookie是 < key,value >结构,它的value值只能存储String类型

      当用户通过浏览器第一次访问服务器时,服务器向浏览器添加cookie信息,cookie中保存了用户的用户名和密码,当用户再次通过同一浏览器访问该浏览器时,服务器会进行自动登录校验,发现cookie中的用户信息,实现自动登录。

cookie的传递
      The servlet sends cookies to the browser by using the HttpServletResponse.addCookie(javax.servlet.http.Cookie) method, which adds fields to HTTP response headers to send cookies to the browser, one at a time.
      The browser returns cookies to the servlet by adding fields to HTTP request headers. Cookies can be retrieved from a request by using the HttpServletRequest.getCookies() method.

      servelt通过HttpServletResponse.addCookie()方法将cookie添加到HTTP响应头的字段中,发送到浏览器。浏览器请求服务器时,在HTTP请求头中添加字段cookie,在服务器使用HttpServletRequest.getCookies()获取cookies

这里写图片描述

##代码实现
LoginServlet

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String uname = request.getParameter("uname");
		String pwd = request.getParameter("pwd");
		UserBiz biz = new UserBiz();
		try {
			BUser user = biz.login(uname, pwd);
			if(user != null){
				request.getSession().setAttribute("user", user);
				//使用cookie实现自动登录
				Cookie cookie = new Cookie("user",uname+","+pwd);
				cookie.setMaxAge(60*60*24);//设置生命周期
				response.addCookie(cookie);
				//统计在线用户数
				OnlineUser.addUser(request.getSession().getId(), user);
				System.out.println(user.getUname() + "登录成功!当前在线人数:" + OnlineUser.getUsers().size());
				request.getRequestDispatcher("/MainSvl").forward(request, response);
			}else{
				request.setAttribute("msg", "用户名或密码错误");
				request.getRequestDispatcher("/WEB-INF/main/login.jsp").forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errMsg", "网络异常,请和管理员联系");
			request.getRequestDispatcher("/error.jsp").forward(request, response);
		}
	}

index.jsp

<%@page import="javax.servlet.jsp.tagext.TryCatchFinally"%>
<%@ page language="java" import="java.util.*,com.icss.biz.*,com.icss.entity.*,com.icss.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
// 自动登录校验
Object  obj = request.getSession().getAttribute("user");
if(obj == null){
	Cookie[] cookies = request.getCookies();
	if(cookies != null){
		for(int i = 0; i < cookies.length; i++){
			Cookie cookie = cookies[i];
			if(cookie.getName().equals("user")){
				String value = cookie.getValue();
				String [] upwd = value.split(",");
				UserBiz biz = new UserBiz();
				try{
					BUser buser = biz.login(upwd[0], upwd[1]);
					if(buser != null){
						request.getSession().setAttribute("user", buser);
					}
				}catch(Exception e){
					Log.logger.error(e.getMessage());
				}
				break;
			}
		}
	}
}
request.getRequestDispatcher("/MainSvl").forward(request,response);
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.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">
	-->
  </head>
  
  <body>
    This is my JSP page. <br>
  </body>
</html>

为什么在jsp页面中进行校验?
      在用户访问通过项目名访问时,会在index.jsp页面转发到MainServlet,进行主页展示。当用户在LogoutServlet退出时,会重定向到MainServlet。如果在MainServlet中进行自动登录校验,则会发生无法退出的情况。


*其他优秀博文*:http://blog.163.com/xiexueyong1987@126/blog/static/126267342201031993557704/
  • 6
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值