gpt4 book ai didi

java - 如何在 Java 中访问 HTTP session

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:46:28 26 4
gpt4 key购买 nike

如何以一种优雅的方式通过 ID 或 Web 应用程序 (Java 2 EE) 中所有当前 Activity 的 http session 获取任何 http session ?

目前我有一个WebSessionListener,创建 session 后,我将其放入ConcurrentHashMap() (map.put(sessionId, sessionObj)),一切正常,我可以随时通过 session ID 从该 map 检索 HTTP session ,但看起来 HttpSession 对象永远不会完成......即使 session 无效, map 仍然引用无效的 session 对象......我也是已阅读this article看起来 WeakHashMap 在我的情况下是 Not Acceptable ......

换句话说,我需要有可能查看任何 HttpSession 甚至获取所有当前 Activity 的 HttpSession 并从那里检索一些属性...

请指教某人:)

更新

由于以下原因,我需要访问 HttpSession 对象:

有时用户执行的一些操作/请求可能会影响另一个并发用户的工作,例如管理员应该禁用用户帐户但该用户当前正在使用系统,在这种情况下我需要向管理员显示一条消息,例如“用户 XXX 当前正在使用系统”因此我需要检查是否有任何持有用户 XXX 凭据的 HttpSession 已经存在并且处于 Activity 状态。所以这就是我需要这种可能性来获得任何 http session 甚至所有 session 的原因。

我当前的实现是:了解所有 session (ConcurrentMap) 的 SessionManager 和将 session 放入/删除 session 到 SessionManager 中的 HttpSessionListener。

我担心可能发生的内存问题,我想与某人讨论这个问题,但目前我清楚地看到一切都应该正常工作,因为当调用 sessionDestroyed() 方法时,所有无效的 session 将从 map 中删除。 ..

非常感谢您的回放,但现在我明白了问题只是想象:)

最佳答案

根据您的说明:

Sometimes user does some actions/requests that may impact the work of another concurrent user, for example admin should disable user account but this user currently working with the system, in this case I need to show a message to admin e.g. "user XXX is currently working with the system" hence I need to check if any HttpSession which holds credentials of user XXX already exists and active. So this is whay I need such possibility to get any http session or even all sessions.

为此,您实际上不需要了解有关 session 的任何信息。您只需要知道哪些用户已登录。为此,您可以完美地让表示已登录用户 的模型对象实现 HttpSessionBindingListener .我当然假设您通过将 User 模型设置/删除为 session 属性来遵循正常的习惯用法来登录/注销用户。

public class User implements HttpSessionBindingListener {

@Override
public void valueBound(HttpSessionBindingEvent event) {
Set<User> logins = (Set<User>) event.getSession().getServletContext().getAttribute("logins");
logins.add(this);
}

@Override
public void valueUnbound(HttpSessionBindingEvent event) {
Set<User> logins = (Set<User>) event.getSession().getServletContext().getAttribute("logins");
logins.remove(this);
}

// @Override equals() and hashCode() as well!

}

然后在您的管理应用程序的某处,只需从 ServletContext 获取登录信息:

Set<User> logins = (Set<User>) servletContext.getAttribute("logins");

关于java - 如何在 Java 中访问 HTTP session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3235997/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com