用户自动登录(异步)

自动登录

* 思路
    1. 当用户登录的成功的时候判断是否勾选了自动登录的checkbox;
    2. 使用cookie来存用户的信息(username,password)
    3. 将cookie写回
    4. 当再次访问到当前的页面(login页面)的时候,可以使用ajax发送一个异步请求
    5. 遍历cookie,获取cookie中是否有username以及password
    6. 查询数据库来进行判断跳转

* 核心代码
    * 存cookie 的servlet
    //登录成功
    //存cookie

    //判断是否有自动登录
    String autologin = request.getParameter("autologin"); //1
    if (autologin != null){
        Cookie cookie = new Cookie("username",u.getUsername());
        Cookie cookie1 = new Cookie("password",u.getPassword());
        //设置cookie的生效时间(默认一周)
        cookie.setMaxAge(60*60*24*7);
        cookie1.setMaxAge(60*60*24*7);
        response.addCookie(cookie);
        response.addCookie(cookie1);
    }
    //存session
    request.getSession().setAttribute("user",u);


    * 异步请求的servlet
    String username = null;
    String password = null;
    //获取cookie
    Cookie[] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
        if (cookie.getName().equalsIgnoreCase("username")){
            username = cookie.getValue();
        }
        if (cookie.getName().equalsIgnoreCase("password")){
            password = cookie.getValue();
        }
    }

    if (username!=null && password!=null){
        //进行登录验证的逻辑
    }

前台

$.ajax("路径",{},function(data){

     //对data进行判断

     if(data.flag){

    //登录跳转

}else{

    //继续登录

}

})

猜你喜欢

转载自blog.csdn.net/qq_35472880/article/details/83018247
今日推荐