如何在java中实现自定义http会话?

2023-12-20

我需要用 Java 实现我自己的 HttpSession 版本。我发现很少有信息可以解释如何实现这一壮举。

我想我的问题是 - 无论应用程序服务器的实现如何,如何覆盖现有的 HttpSession?

我确实读过一本高质量但相当老的读物,它帮助我实现了我的目标 -http://java.sun.com/developer/technicalArticles/Servlets/ServletControl/ http://java.sun.com/developer/technicalArticles/Servlets/ServletControl/

还有其他方法吗?


有两种方式。

“包裹”原来的HttpSession在你自己的HttpServletRequestWrapper执行。

我不久前做了这个,用于使用 Hazelcast 和 Spring Session 对分布式会话进行集群。

Here http://docs.spring.io/spring-session/docs/current/reference/html5/#httpsession-how解释得很好。

首先,实现自己的HttpServletRequestWrapper

public class SessionRepositoryRequestWrapper extends HttpServletRequestWrapper {

        public SessionRepositoryRequestWrapper(HttpServletRequest original) {
                super(original);
        }

        public HttpSession getSession() {
                return getSession(true);
        }

        public HttpSession getSession(boolean createNew) {
                // create an HttpSession implementation from Spring Session
        }

        // ... other methods delegate to the original HttpServletRequest ...
}

之后,从您自己的过滤器中,包装原始的HttpSession,并将其放入FilterChain由您的 Servlet 容器提供。

public class SessionRepositoryFilter implements Filter {

        public doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
                HttpServletRequest httpRequest = (HttpServletRequest) request;
                SessionRepositoryRequestWrapper customRequest =
                        new SessionRepositoryRequestWrapper(httpRequest);

                chain.doFilter(customRequest, response, chain);
        }

        // ...
}

最后,在 web.xml 的开头设置您的过滤器,以确保它先于其他过滤器执行。

实现它的第二种方式是向您的 Servlet 容器提供您的自定义 SessionManager。

例如,在Tomcat 7 https://tomcat.apache.org/tomcat-7.0-doc/config/manager.html.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在java中实现自定义http会话? 的相关文章

随机推荐