java 如何从 SessionID 获取 HttpSession 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1251339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:49:22  来源:igfitidea点击:

How to obtain an HttpSession Object from SessionID?

javaservletshttpsession

提问by Bahaa Zaid

I want to invalidate sessions of users based on some Event. I store their sessionID, how to get their HttpSession from this ID? The HttpSessionContext class is deprecated with no replacement.

我想根据某些事件使用户会话无效。我存储他们的 sessionID,如何从这个 ID 获取他们的 HttpSession?HttpSessionContext 类已弃用,没有替代品。

采纳答案by ZZ Coder

Servlet 2.2 specifically deprecated this for security reasons so there shouldn't be any official way to do this. Not recommended but you can can try to use Manager.findSession() if you use Tomcat.

出于安全原因,Servlet 2.2 特别弃用了这一点,因此不应该有任何官方方法来做到这一点。不推荐,但如果您使用 Tomcat,您可以尝试使用 Manager.findSession()。

I just removed HttpSession from my application. It's really hard to keep sessions in sync when many servers are running. We tried to tweak it by writing our own manager but can never get it work right. Finally, we wrote our own session implementation with about 500-lines of code and it works much better.

我刚刚从我的应用程序中删除了 HttpSession。当许多服务器正在运行时,保持会话同步真的很困难。我们试图通过编写我们自己的经理来调整它,但永远无法让它正常工作。最后,我们用大约 500 行代码编写了自己的会话实现,并且效果更好。

回答by Niger

The methods that are already doing this are deprecated. But you can implement the your idea useing HttpSessionListener, when a new session is created store it in a HashMap with session id as a key and object is actual HttpSessionObject. You can get the reference by this.

不推荐使用已经执行此操作的方法。但是您可以使用 HttpSessionListener 实现您的想法,当创建新会话时,将其存储在 HashMap 中,会话 ID 作为键,对象是实际的 HttpSessionObject。您可以通过此获得参考。