全部
常见问题
产品动态
精选推荐

如何实现网页的自动登录

管理 管理 编辑 删除

了解cookie

我们在浏览器进行操作的时候,有时候会在我们的浏览器中留下cookie数据,他不同于session域对象,cookie对象有这自己的生命周期,只要生命周期还在,那么cookie就不会消失,具体session和cookie的不同:

1)存储的位置不同

Cookie存储在浏览器端

Session存储在服务器端:session携带cookie名称jsessionid存在浏览器端存的

2)存储数据类型不一样

Cooike的构造方法:

public Cooike(String name,String value):cookie只能存储String类型

HttpSession.setAttribute(String name,Object value):可以存储任意类型

3)存储的数据大小是否有限制

Cookie在浏览器端是有限制的,一个站点下的cookie数据有限制的;

HttSession可以不断的设置数据,没有限制

c4cd3202303041131022869.png

这张图就可以看到cookie的创建时间和到期时间,生命周期是一个月.

自动登录

在了解完cookie后,可以开始进行自动登录的操作了,我们可以通过获取到浏览器中的cookie,来获取到自动登录的账户的密码账户,然后让他进行自动登录,不需要进行账户密码的输入.

那么首先要在前端,当我们勾选了自动登录后,让我们的后端java吧此次登录的账户密码添加到浏览器中的cookie中:

<input type="checkbox" name="autolog" value="auto"> 自动登录

勾选后,autolog的值就为auto了,那么后端读取到名字为autolog的值,如果为auto就代表了自己勾选了账户密码.接下来进行后端的操作:

    public void log(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session1 = request.getSession();
        session1.invalidate();
        String username = request.getParameter( "username" );
        String password = request.getParameter( "password" );
        String autolog = request.getParameter( "autolog" );
        String rpassword = MD5Utils.md5( password );
        System.out.println( "前端输入的用户名是" + username );
        NewServiceDao newServiceDao = new NewServiceDaoImpl();
        User user = newServiceDao.logService( username, rpassword );
        System.out.println( user );
        if (user != null) {
            if (user.getState() == 1) {
                HttpSession session = request.getSession();
                session.setAttribute( "user", user );
                if (autolog.equals( "auto" )) {	//读取数据是否为auto,判断是否要将数据添加
                    String count = username + "=" + rpassword;
                //注意,cookie的数据只能存储字符串类型,不可以添加object,所以我们自己规定格式			
                //用等号来分割账户和密码
                    count = URLEncoder.encode( count, "utf-8" );
                    //为了防止被人看到账户密码,给他进行转换格式的添加,并且防止了中文乱码
                    Cookie auto = new Cookie( "auto", count );
                    //新建一个cookie对象,cookie对象的名字为auto,值为刚刚拼接的账户密码的字符串
                    auto.setMaxAge( 60 * 60 * 24 * 30 );
                    //设置cookie对象的生命周期
                    response.addCookie( auto );
                    //将此次cookie对象添加到浏览器中
                } else {
                    Cookie auto = new Cookie( "auto", "" );
                    auto.setMaxAge( 0 );
                    //生命周期为0意思是删除cookie
                    response.addCookie( auto );
                }
                response.sendRedirect( request.getContextPath() + "/jsp" );
            } else {
                HttpSession session = request.getSession();
                session.setAttribute( "user", user );
                String s = JiHuo.jiHuo();
                MailUtils.sendMail( user.getEmail(), s, "激活码" );
                session.setAttribute( "codee", s );
                response.sendRedirect( request.getContextPath() + "/jsp/zhong.jsp" );
            }
        }
    }

这次操作后,我们的cookie对象已经添加到浏览器中了,我们可以去看看

47986202303041132361514.png

可以看到名字为auto的cookie,他的生命周期还有内容,现在就要去让他去进行自动登录了.
首先写一个过滤器,当我们点击登录,或者网址输入登录界面的时候,直接让他进行自动登录.

@WebFilter(value = "/jsp/login.jsp",dispatcherTypes = {DispatcherType.REQUEST,DispatcherType.FORWARD})
//DispatcherType.REQUEST地址栏直接访问     DispatcherType.FORWARD 请求转发
public class AutoFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化了");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            HttpServletRequest request1=(HttpServletRequest) request;
            HttpServletResponse response1=(HttpServletResponse)response;
            Cookie[] cookies = request1.getCookies();
            //获取网页中的全部cookie对象
            if (cookies!=null){
            //判断是否为空
                String value=null;
                for (Cookie cookie:cookies){	//遍历全部的cookie对象
                    if (cookie.getName().equals( "auto" )){//找到名字为auto的cookie对象
                       value = cookie.getValue();
                       //读取到他的value值
                    }
                }
                if (value!=null){
                //如果value值不为空,则代表有名字为这个的cookie值
                    value= URLDecoder.decode( value,"utf-8" );
                    //吧格式转换回来
                    String[] split = value.split( "=" );
                    //因为我们规定了用等号切割账户密码,所以获取切割后的数组
                    String username = split[0];//账户
                    String password = split[1];//密码
                    NewServiceDao serviceDao = new NewServiceDaoImpl();
                    User user = serviceDao.logService( username, password );
                    //获取到user对象
                    if (user!=null){
                        HttpSession session = request1.getSession();
                        session.setAttribute( "user",user );
                        //吧user对象存储进域对象,并且跳转到登录后的界面
                        response1.sendRedirect( request1.getContextPath()+"/jsp" );
                    }
                }
                else{
                //如果不是,则放行
                    chain.doFilter( request1,response1 );
                }
        }else{
        //如果不是,则放行
                chain.doFilter( request1,response1 );
            }
    }

    @Override
    public void destroy() {
        System.out.println("自动登录器销毁");
    }
}

过滤器的原理:

头部的@WebFilter里,value值是在那个界面会进行过滤,比如现在过滤器中value = “/jsp/login.jsp”,则代表当在网页为/jsp/login.jsp的网页中的时候,会进入过滤器,进行操作,chain.doFilter(request,response)的意思是进行放行操作,让程序走自己该走的地方,写完这些后,当我们已经有了cookie对象名字为auto的时候,让他进行自动登录

退出账户

现在如果我想切换账户,但是因为cookie对象存在,所以我们现在除非手动删除cookie,否则不管咋样,进导登录界面后,都会自动登录了,那么为了不去手动删除,而是通过点击退出,来让账户退出,则我们需要写一个方法:

    public void change(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals( "auto" )) {
                //获取这个名字为auto的cookie
                    System.out.println("进来了");
                    cookie.setMaxAge(0);
                    //生命周期给他赋为0则代表删除了他
                    response.addCookie( cookie );
                    HttpSession session = request.getSession();
                    session.invalidate();
                    //清空session域
                    response.sendRedirect( request.getContextPath()+"/jsp/login.jsp" );
                }
            }
        }else{
            try {
                request.getRequestDispatcher( "/jsp/login.jsp" ).forward( request,response );
            } catch (ServletException e) {
                e.printStackTrace();
            }
        }
    }

这样,就吧cookie对象为auto的删除掉了


CRMEB-慕白寒窗雪 最后编辑于2023-03-04 11:34:22

快捷回复
回复({{post_count}}) {{!is_user ? '我的回复' :'全部回复'}}
回复从新到旧

{{item.user_info.nickname ? item.user_info.nickname : item.user_name}}

作者 管理员 企业

{{item.floor}}# 同步到gitee 已同步到gitee {{item.is_suggest==1? '取消推荐': '推荐'}}
{{item.floor}}#
{{item.user_info.title}}
附件

{{itemf.name}}

{{item.created_at}}  {{item.ip_address}}
{{item.like_count}}
{{item.showReply ? '取消回复' : '回复'}}
删除
回复
回复

{{itemc.user_info.nickname}}

{{itemc.user_name}}

作者 管理员 企业

回复 {{itemc.comment_user_info.nickname}}

附件

{{itemf.name}}

{{itemc.created_at}}   {{itemc.ip_address}}
{{itemc.like_count}}
{{itemc.showReply ? '取消回复' : '回复'}}
删除
回复
回复
查看更多
回复
回复
1325
{{like_count}}
{{collect_count}}
添加回复 ({{post_count}})

相关推荐

CRMEB-慕白寒窗雪 作者
社区运营专员---高冷のBoy | 呆萌のGirl

回答

2123

发布

1773

经验

44564

快速安全登录

使用微信扫码登录
{{item.label}} {{item.label}} {{item.label}} 板块推荐 常见问题 产品动态 精选推荐 首页头条 首页动态 首页推荐
加精
取 消 确 定
回复
回复
问题:
问题自动获取的帖子内容,不准确时需要手动修改. [获取答案]
答案:
提交
bug 需求 取 消 确 定

微信登录/注册

切换手机号登录

{{ bind_phone ? '绑定手机' : '手机登录'}}

{{codeText}}
切换微信登录/注册
暂不绑定
CRMEB客服

CRMEB咨询热线 咨询热线

400-8888-794

微信扫码咨询

CRMEB开源商城下载 开源下载 CRMEB官方论坛 帮助文档
返回顶部 返回顶部
CRMEB客服