WEB系统防止同一账号,同时在多个不同设备登录。

来源:互联网 发布:techsmith软件 编辑:程序博客网 时间:2024/05/21 20:28

方案一、在用户表新增三个字段分别存储,用户登录口令、上次登录IP地址、上次登录时间,在登录成功后,生成唯一用户登录口令,把用户登录口令、上次登录IP地址、上次登录时间存储到SESSION,并相应的存储到用户表。然后提示用户 上次登录IP地址、上次登录时间。(也可以把IP地址转为具体地区展示)

方案二、判断是否已经登录时,先判断是否登录状态? 再读取SESSION的用户登录口令,如果登录口令不为空,则把登录口令的值与用户表的登录口令比较,若不一致,则提示用户“您的账号在其他设备登录”,并且退出登录(清楚登录状态)

方案三、同时使用servletContext和cookie保存用户信息 ,通过servletContext判断用户是否登录,和cookie判断用户是否在同一设备登录。
提供方案三代码:
LoginServlet

ServletContext sc = getServletContext();Cookie[] cookies = httpRequest.getCookies();boolean flag = false;for(int i = 0; i < cookies.length; i++){    String key = cookies[i].getName();    if(userId.equals(key)){        flag = true;    }}String old_session = (HttpSession)sc.getAttribute(userId);if(old_session != null){    if(!flag){            SystemOut.out.println(“该用户已在其他设备登录!”);            return false;    }}//用户登录成功sc.setAttribute(userId,"用户");Cookie cookie = new Cookie(userId,"用户");httpResponse.addCookie(cookie);

注销登录
LogOutServlet

ServletContext sc = getServletContext();sc.removeAttribute(userId);//删除CookieCookie cookie = new Cookie(userId,"用户");cookiesetMaxAge(0);httpResponse.addCookie(cookie);

“`

0 0