如何在java中实现自定义http会话?
我需要用 Java 实现我自己的 HttpSession 版本。我发现很少有信息可以解释如何实现这一壮举。
我想我的问题是 - 无论应用程序服务器的实现如何,如何覆盖现有的 HttpSession?
我确实遇到了一本高质量但相当旧的读物,它帮助我实现了我的目标 - http:// /java.sun.com/developer/technicalArticles/Servlets/ServletControl/
还有其他方法吗?
I will need to implement my own version of HttpSession in Java. I have found very little information which explains how achieve such a feat.
I guess my problem is - how do I override the existing HttpSession no matter the application server's implementation?
I did run across a quality but rather old read which helps me achieve my goal - http://java.sun.com/developer/technicalArticles/Servlets/ServletControl/
Are there any other approaches?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有两种方式。
在您自己的
HttpServletRequestWrapper
实现中“包装”原始的HttpSession
。我不久前做了这个,用于使用 Hazelcast 和 Spring Session 集群分布式会话。
这里解释得很好。
首先,实现您自己的
HttpServletRequestWrapper
之后,从您自己的 Filter 中,包装原始的
HttpSession
,并将其放入您的 Servlet Container 提供的FilterChain
中。最后,在 web.xml 的开头设置您的过滤器,以确保它先于其他过滤器执行。
实现它的第二种方式是向 Servlet 容器提供自定义 SessionManager。
例如,在 Tomcat 7。
Its two ways.
"Wrapping" the original
HttpSession
in your ownHttpServletRequestWrapper
implementation.I made this a short time ago for clustering distributed sessions with Hazelcast and Spring Session.
Here is explained pretty well.
First, implement your own
HttpServletRequestWrapper
After, from your own Filter, wraps the original
HttpSession
, and put it inside theFilterChain
provided by your Servlet Container.Finally, set your Filter at the beginning in the web.xml to ensure it performs before any other.
The second manner to achieve it is providing to your Servlet Container your custom SessionManager.
For example, in Tomcat 7.
创建一个新类,并实现 HttpSession:
免责声明:我自己还没有对此进行测试:
然后编写一个 url 模式为 /* 的过滤器并扩展
HttpServletRequestWrapper
。您的包装器应在getSession(boolean)
中返回您的自定义HttpSession
类。在过滤器中,使用您自己的
HttpServletRequestWrapper
。Create a new class, and implement HttpSession:
Disclaimer: I have not tested this myself:
Then write a filter with a url-pattern of /* and extend
HttpServletRequestWrapper
. Your wrapper should return your customHttpSession
class ingetSession(boolean)
.In the filter, use your own
HttpServletRequestWrapper
.由于 HttpSession 实现是由 J2EE 容器提供的,因此以可移植的方式在不同容器之间工作似乎并不容易。
但是,要实现类似的结果,您可以实现 javax.servlet.Filter 和 javax.servlet.HttpSessionListener ,并在过滤器中包装 ServletRequest 和 ServletResponse,如 使用 Hazelcast 和 Tomcat 的 Spring Boot。
It doesn't seem like it's easily doable in a portable fashion that would work among different containers, since the HttpSession implementation is provided by the J2EE container.
However, to achieve a similar result, you can implement a javax.servlet.Filter and javax.servlet.HttpSessionListener and in your filter, wrap the ServletRequest and ServletResponse, such as described in Spring Boot with Hazelcast and Tomcat.