用户自动登录(异步)

自动登录

* 思路
    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{

    //继续登录

}

})

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值