• Cookie:实现网站十天内免密登录


    一、Cookie是什么:

    session的实现原理中,每一个session对象都会关联一个sessionid,例如:jsessionid=xxxxxxxxxxxx
    以上的这个键值对数据其实就是cookie对象。

    二、Cookie作用:

    1. cookie和session机制其实都是为了保存会话状态
    2. cookie是将会话的状态保存在浏览器客户端上。(cookie数据存储在浏览器客户端上的)
    3. session是将会话的状态保存在服务器端上。(session对象是存储在服务器上)
    4. cookie是保存在浏览器上的key=value键值对,可以保存账号密码sessionid等,根据需求在需要的地方创建cookie。 只要浏览器不关闭,用户再次发送请求的时候,会根据URL在request请求的请求头中自动将部分需要的cookie发送给服务器。
    5. 为什么要有cookie和session机制呢?因为HTTP协议是无状态协议。

    三、Cookie保存在什么地方?

    1. 可以保存在浏览器运行内存中。(浏览器只要关闭cookie就消失了)
    2. 可以保存在硬盘文件中。(永久保存。)

    四、Cookie和Session区别:

    一个保存在浏览器客户端,一个保存在服务器端。

    四、Cookie用法:

    位于jakarta.servlet.http.Cookie包下;

    1. 创建cookie对象:
    new Cookie(key,value);
    
    • 1
    1. java程序把cookie数据发送给浏览器:
    response.addCookie(cookie对象)
    
    • 1
    1. 设置cookie失效时间:
      只要设置了cookie失效时间,这个cookie就会存储在硬盘文件中。不设置就会存储在浏览器运行内存中,浏览器关闭cookie失效。
    cookie.setMaxAge(s);//秒为单位
    
    • 1
    1. 删除该cookie:
    cookie.setMaxAge(0);
    
    • 1
    1. 设置cookie接收路径:
      表示只要URL请求路径是servlet13下的路径,浏览器都会发送这个cookie给服务器。
      系统默认设置是生成cookie的路径(/servlet13/abc/list)的上一层路径(servlet13/abc)。
    cookie.setPath("/servlet13")
    
    • 1
    1. 获取浏览器发送给服务器的cookie:
      如果没有接收到cookie,返回值是null。
    request.getCookies();
    
    • 1
    1. 案例:网站实现十天内免登录
      (1)首先在用户登录界面创建复选框,勾选复选框后提交的话浏览器会发送复选框属性name=value的键值对给服务器,服务器用一个if语句判断是否收到这样一个键值对("value").equals(request.getParameter("name")),如果返回true,创建两个cookie对象分别存储用户名和密码,设置cookie失效时间、响应路径,把cookie通过HTTP响应报文传给浏览器保存。
    Cookie cookie1 = new Cookie("username",request.getParameter("username"));//创建cookie
    Cookie cookie2 = new Cookie("password",request.getParameter("password"));
    cookie1.setMaxAge(60*60*24*10);//设置cookie失效时间
    cookie2.setMaxAge(60*60*24*10);
    cookie1.setPath(request.getContextPath());//设置响应路径
    cookie2.setPath(request.getContextPath());
    response.addCookie(cookie1);//cookie传给浏览器保存
    response.addCookie(cookie2);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    (2)创建一个servlet,用于判断是否用户免密登录,用户输入我们网站的URL,有两种可能:1.如果浏览器通过get请求报文传给服务器cookie了,那就说明用户上次点击了免密登录复选框,所以用户的浏览器存有上面的两个cookie,我们只需验证cookie中的用户名密码是否正确即可,正确的话直接让的话用户可以直接转到URL对应的页面。2. 如果浏览器没有发送cookie,服务器没有捕捉到对应的cookie,那不管用户输入了我们webapp的哪个URL,都强制用户跳转到登录页面。

    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    @WebServlet("/welcome")
    public class WelcomeServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            Cookie cookies[] = request.getCookies();
            String username = null;
            String password = null;
            if (cookies != null) {//判断浏览器的请求行的cookie字段是否有信息
                for (Cookie cookie : cookies) {
                    if ("username".equals(cookie.getName())){//获取cookie中的用户名
                        username = cookie.getValue();
                    }
                    if("password".equals(cookie.getName())){//获取cookie中的密码
                        password = cookie.getValue();
                    }
                }
            }
            if(username!=null && password!=null){//用户之前登陆成功且设置了免登录,浏览器保存了cookie
                //验证用户名密码是否正确:为了防止用户点击免登录后改密码
                Connection connection = null;
                PreparedStatement preparedStatement = null;
                ResultSet resultSet = null;
                boolean flag = false;
                try {
                    connection = DButil.getConnection();
                    preparedStatement = connection.prepareStatement("select username,password from t_user where username=? and password=?");
                    preparedStatement.setString(1, username);
                    preparedStatement.setString(2, password);
                    resultSet = preparedStatement.executeQuery();
                    if (resultSet.next()) {//cookie中的用户名和密码正确
                        flag = true;
                        //获取session,没有则新建
                        HttpSession session = request.getSession();
                        //将用户登录成功的信息存到会话域
                        session.setAttribute("username",username);
                        //重定向,登陆成功后转到list连接数据库获取信息,然后转到list.jsp页面展示
                        response.sendRedirect(request.getContextPath()+"/dept/list");
                    }
                    if (flag == false) {//cookie中的用户名和密码错误
                        //重定向,密码错误后转到失败页面
                        response.sendRedirect(request.getContextPath()+"/error.jsp");
                    }
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                } finally {
                    DButil.close(connection, preparedStatement, resultSet);
                }
            }else{//用户之前没有登录过,表示该用户第一次访问网站
                //重定向,跳转到登录页面
                response.sendRedirect(request.getContextPath()+"/index.jsp");
            }
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60

    (3)点击退出按钮删除cookie,session,下次登录需要重新输入用户名密码:

    private void doLogout(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
            HttpSession session = request.getSession(false);
            if (session != null){
                session.invalidate();//手动销毁session
                //手动销毁cookie
                Cookie[] cookies = request.getCookies();
                if (cookies != null) {
                    for (Cookie cookie : cookies) {
                        cookie.setPath(request.getContextPath());//要删除根路径下的cookie,只删除子路径下的cookie没用
                        cookie.setMaxAge(0);
                        response.addCookie(cookie);
                    }
                }
                //重定向到登录页面
                response.sendRedirect(request.getContextPath());
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    (3)将欢迎页由登陆界面改为该servlet,每次用户访问本站将首先执行该servlet判断是否需要登陆:

    
    <welcome-file-list>
        <welcome-file>welcomewelcome-file>
    welcome-file-list>
    
    • 1
    • 2
    • 3
    • 4
  • 相关阅读:
    面试算法31:最近最少使用缓存
    前端新轮子Nue JS,号称要打造全新的Web生态!!!
    kotlin不同对象的list合并
    三端植物大战僵尸杂交版来了
    微信小程序 --- 简易双向绑定
    C复习-函数指针+字符串常量
    如何通过axios拦截器,给除了登录请求以外,axios的所有异步请求添加JWT令牌!
    武汉新时标文化传媒有限公司:如何做好短视频直播间的流量?
    会议OA项目(三)---我的会议(会议排座、送审)
    Java之Map集合
  • 原文地址:https://blog.csdn.net/m0_53881899/article/details/126450858