现在的很多网站,在你登录时一般都会有个复选框让你选择是否记录你的登录状态,当勾选时,下次再访问该网站就会为你自动登录,免去再次输入账号密码的麻烦,带来一定的便利性。我们要做的就是实现这个功能。

先来看看它的几种实现方式:

[1] 使用Cookie来保存,这是最常见的方法,本文“记住我的登录状态”功能的实现正式基于这种方式的。

[2] 使用URL附加信息的方式,也就是像我们经常看到JSP网站会有xxx.jsp?JSESSIONID=xxxxxxxxx一样。

[3] 第三种方式是在页面表单里面增加隐藏域,这种方式实际上和第二种方式一样,只不过前者通过GET方式发送数据,后者使用POST方式发送数据。但是明显后者比较麻烦。

我们采用的是最常用也是最简单的第一种方式,这里需要对session和cookie的机制有一定的了解,还不清楚的请自行查阅资料。实现这个功能主要有三具步骤:

1、在登录成功后将用户信息发送到客户端

在登录成功后,后台以cookie的方式将加过密的用户信息发送到客户端浏览器,由客户端浏览器进行保存:

if (isRemember != null && isRemember) {
    Cookie cookie = new Cookie("loginName", user.getLoginName());
    //设置Cookie的过期时间为一周
    cookie.setMaxAge(60 * 60 * 24 * 7);
    //设置路径
    cookie.setPath(request.getContextPath());
    response.addCookie(cookie);
    cookie = new Cookie("password", user.getPassword());
    cookie.setMaxAge(60 * 60 * 24 * 7);
    cookie.setPath(request.getContextPath());
    response.addCookie(cookie);
}

isRemember 即判断是否勾选了记住登录状态的复选框。

2、获取保存在cookie中的用户信息

上面我们已经将用户信息存放在了cookie当中,在下次访问时就可以取用尝试自动登录了,一般是在session拦截器中,核心代码:

/**
 * 记住状态自动登录
 * 
 * @param request
 * @return
 */
private UserVo rememberAutoLogin(HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (cookies == null || cookies.length == 0) {
        return null;
    }
    String loginName = null;
    String password = null;
    for (Cookie cookie : cookies) {
        if (StringUtils.equals(cookie.getName(), "loginName")) {
            loginName = cookie.getValue();
        } else if (StringUtils.equals(cookie.getName(), "password")) {
            password = cookie.getValue();
        }
    }
    if (StringUtils.isNotBlank(loginName) && StringUtils.isNotBlank(password)) {
        WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
        UserService userService = (UserService) wac.getBean("userServiceImpl");
        UserVo userVo = userService.rememberAutoLogin(loginName, password);
        WebUtils.setSessionAttribute(request, UserVo.SESSION_KEY, userVo);
        return userVo;
    }
    return null;
}

这里,因为是在拦截器中所以没有使用service注入的方式,而是采用了ApplicationContext来获取bean,原理上都一样。

3、移除记住的登录状态

有了记住登录功能,自然要有移除掉这个状态的功能,不然会导致用户无法退出登录。在我们原来退出登录的代码中增加如下操作:

Cookie[] cookies = request.getCookies();
if (cookies != null) {
    for (Cookie cookie : cookies) {
        if (StringUtils.equals("loginName", cookie.getName())) {
            cookie.setMaxAge(0);
            cookie.setPath(request.getContextPath());
            response.addCookie(cookie);
        } else if (StringUtils.equals("password", cookie.getName())) {
            cookie.setMaxAge(0);
            cookie.setPath(request.getContextPath());
            response.addCookie(cookie);
        }
    }
}

将MaxAge设置为0即表示删除cookie操作,这里不要忘记加上cookie.setPath(request.getContextPath());这一行,跟前面保存时的路径一致,因为cookie是无法获取到这些额外的信息的,所以仍然要进行设置,不然有可能导致cookie无法删除的情况。

你可能感兴趣的内容
2条评论
easycoder 1年前
顶,楼主是否要考虑这样保存用户名和密码不安全
dexcoderdexcoder 1年前
加密,加盐

selfly

交流QQ群:32261424
Owner