java 防止用户重复登录_JAVA 如何避免用户的重复登录
展開全部
讀懂下面代碼,就知道如何實現 一個用戶登陸 踢掉之前登陸的用戶了//第一步
//?此監聽62616964757a686964616fe4b893e5b19e31333337626166器用來監聽用戶在對session做操作的時候執行相應的方法
import?javax.servlet.http.HttpSession;
import?javax.servlet.http.HttpSessionAttributeListener;
import?javax.servlet.http.HttpSessionBindingEvent;
import?javax.servlet.http.HttpSessionEvent;
import?javax.servlet.http.HttpSessionListener;
import?java.util.*;
public?class?SessionListener?implements?HttpSessionListener?,
HttpSessionAttributeListener{
//?保存當前登錄的所有用戶
public?static?Map?loginUser=
new?HashMap();
//?用這個作為session中的key
public?static?String?SESSION_LOGIN_NAME?=?"user_id_key";
//session創建時調用這個方法
public?void?sessionCreated(HttpSessionEvent?arg0)?{
}
//Session失效或者過期的時候調用的這個方法,
public?void?sessionDestroyed(HttpSessionEvent?se)?{
//?如果session超時,?則從map中移除這個用戶
try?{
loginUser.remove(se.getSession());
}catch?(Exception?e)?{
e.printStackTrace();
}
}
//執行setAttribute的時候,?當這個屬性本來不存在于Session中時,?調用這個方法.
public?void?attributeAdded(HttpSessionBindingEvent?se)?{
//?如果添加的屬性是用戶名,?則加入map中
if?(se.getName().equals(SESSION_LOGIN_NAME))?{
loginUser.put(se.getSession(),?Long.valueOf(se.getValue().toString()));
}
}
//當執行removeAttribute時調用的方法
public?void?attributeRemoved(HttpSessionBindingEvent?se)?{
//?如果移除的屬性是用戶名,?則從map中移除
if?(se.getName().equals(SESSION_LOGIN_NAME))?{
try?{
loginUser.remove(se.getSession());
}?catch?(Exception?e)?{
}
}
}
//當執行setAttribute時?,如果這個屬性已經存在,?覆蓋屬性的時候,?調用這個方法
public?void?attributeReplaced(HttpSessionBindingEvent?se)?{
//?如果改變的屬性是用戶名,?則跟著改變map
if?(se.getName().equals(SESSION_LOGIN_NAME))?{
loginUser.put(se.getSession(),?Long.valueOf(se.getValue().toString()));
}
}
//別忘了到你的web.xml中去配置一下listener
//第二步
//寫一個判斷用戶是否已經登陸的方法
public?boolean?isLogonUser(Long?userId)?{
Set?keys?=?SessionListener.loginUser.keySet();
for?(HttpSession?key?:?keys)?{
if?(SessionListener.loginUser.get(key).equals(userId))?{
return?true;
}
}
return?false;
}
//第三步
//在用戶登陸的action.method,或者是loginServlet.doGet/doPost中
//判斷用戶名、密碼都OK后,再調用第二步的方法,參數為用戶ID;true則表示該用戶已經登陸
//第四步
//用戶窗口關閉/或者用戶退出的時候,*一定要???request.getSession().invalidate()
//用戶窗口關閉js
//關閉窗口時調用此方法
function?window.onunload(){
if((window.screenLeft>=10000?&&?window.screenTop>=10000)||event.altKey)
{
//清除當前session,使用jquery?提供的方法
$.post("${base}/ClearSession.wp");
//?[?${base}/ClearSession.wp?]這是一個請求,
//請求到自己寫的ClearSessionServlet
//?在此ClearSessionServlet中重寫doPost方法,
//?內容為?request.getSession().invalidate()
}
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的java 防止用户重复登录_JAVA 如何避免用户的重复登录的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java excel sheet页_Ja
- 下一篇: java中static作用_java中s