使用Cookie实现自动登录

来源:互联网 发布:网络安全检查通报 编辑:程序博客网 时间:2024/05/16 18:25

说明

      在之前的博文《了解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/

原创粉丝点击