ログインしているユーザーのアクティブなセッションの数を知る必要があります。経由でHttpServletRequest
、現在ログインしているプリンシパルを取得できます -> getUserPrincipal()
。そのプリンシパルのアクティブなセッションの数を照会する方法はありますか?
1 に答える
1
サーブレット Api がこれを提供するとは思わない。しかし、機能的にそれを行うことができます。
ユーザーとセッション オブジェクトのマップを作成します。
Map<User, HttpSession> logggedUserMap = new HashMap<User, HttpSession>();
ユーザーがログインしている間にエントリを追加し、ログアウトすると削除します。
したがって、logggedUserMap.size()
値は開いているユーザー セッションの合計です。
HttpSessionBindingListenerを使用します。これは、セッションからバインドまたはアンバインドされたコード セッション属性の任意の場所を追跡します。
クラスを作成
class SessionObject implements HttpSessionBindingListener {
String message = "";
User loggedInUser;
Logger log = Logger.getLogger(SessionObject.class);
public SessionObject(User loggedInUser) {
this.loggedInUser=loggedInUser;
}
public void valueBound(HttpSessionBindingEvent event) {
log.info("=========in valueBound method==============");
HttpSession session =LoggedInUserSessionUtil.getLogggedUserMap().get(loggedInUser);
try{
if (session != null && session.getLastAccessedTime() != 0) {
message = "ALL_READY_LOGGEDIN";
return;
}
}catch(IllegalStateException e){
e.printStackTrace();
session = LoggedInUserSessionUtil.removeLoggedUser(loggedInUser);
}
System.out.println("*************************************"+event.getSession().getId() +"------"+loggedInUser+"*********************************************");
log.info("=========valueBound putting in user map==============");
LoggedInUserSessionUtil.getLogggedUserMap().put(loggedInUser, event.getSession());
return;
}
public void valueUnbound(HttpSessionBindingEvent event) {
// This work already doing in Force logout servlet
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
ユーザーがログインしている間に、このオブジェクト インスタンスをバインドします。
SessionObject sessionObj = new SessionObject(loggedInUser);
req.getSession().setAttribute("Binder.object",sessionObj);
于 2013-06-04T14:24:32.193 に答える