功能:当你在一台电脑上登录了账号,然后又在另外一台电脑上登录(同一个账号),就立马提示前一台账号下线通知,就和QQ等下线通知一样。
实现思路:将用户的登录信息保存在application和session内置作用域内, 然后在首页写个定时器,轮询某ajax方法(检查application和session是否相等,不相等则弹出“用户在其他地方登录信息”)。
示例代码:
1、登录时判断该用户的application是否存在,如果已经存在,换个其他值。
HttpSession session = ServletActionContext.getRequest().getSession(); ServletContext application = session.getServletContext(); if(application.getAttribute(t_user.getName())==null){ application.setAttribute(t_user.getName(), "1"); session.setAttribute(t_user.getName(), "1"); }else{ if(application.getAttribute(t_user.getName()).toString().equals("1")){ application.setAttribute(t_user.getName(), "2"); session.setAttribute(t_user.getName(), "2"); }else{ application.setAttribute(t_user.getName(), "1"); session.setAttribute(t_user.getName(), "1"); } }
2、Ajax代码:
public String reLoginAjax() throws Exception{ HttpSession session = ServletActionContext.getRequest().getSession(); ServletContext application = session.getServletContext(); System.out.println(session.getAttribute("userName").toString()+"开始监控了。。。。。。。"); msg = "true"; String userName = session.getAttribute("userName").toString(); if(!session.getAttribute(userName).equals(application.getAttribute(userName))){ msg = "false"; } return "success"; }
3、首页加定时器,因为是轮询application内容,所有消耗很少。
var timer = null; function reLogin(){ var loginName = "aaa"; var url = 'ReLoginAjax.action'; var params = { loginName:loginName }; jQuery.post(url, params, callbackFun1, 'json'); } function callbackFun1(data){ var msg = data['msg']; if(msg=='false'){ clearInterval(timer); alert("该用户在其他地方登录!"); window.top.location.href="login.jsp"; } } timer = setInterval(function(){ reLogin(); }, 5000);