我需要在Java中实现我自己的HttpSession版本。我发现很少有信息可以解释如何实现这样的壮举。
我想我的问题是 - 无论应用服务器的实现如何,我如何覆盖现有的HttpSession?
我确实遇到了一个质量相当旧的阅读,这有助于我实现目标 - http://java.sun.com/developer/technicalArticles/Servlets/ServletControl/
还有其他方法吗?
答案 0 :(得分:5)
它的两种方式。
“封装”您自己的HttpSession
实施中的原始HttpServletRequestWrapper
。
我很久以前就用Hazelcast和Spring Session集群分布式会话。
Here解释得很好。
首先,实施您自己的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
,并将其放入您的Servlet容器提供的FilterChain
内。
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的开头设置Filter,以确保它在任何其他之前执行。
实现它的第二种方式是向您的Servlet容器提供自定义SessionManager。
例如,在Tomcat 7。
答案 1 :(得分:4)
创建一个新类,并实现HttpSession:
public class MyHttpSession implements javax.servlet.http.HttpSession {
// and implement all the methods
}
免责声明:我自己没有测试过:
然后编写一个url-pattern为/ *并扩展HttpServletRequestWrapper
的过滤器。您的包装器应该返回HttpSession
中的自定义getSession(boolean)
类。
在过滤器中,使用您自己的HttpServletRequestWrapper
。
答案 2 :(得分:1)
由于HttpSession实现是由J2EE容器提供的,因此它似乎很容易以便携式方式在不同容器之间工作。
但是,要实现类似的结果,可以实现javax.servlet.Filter和javax.servlet.HttpSessionListener,并在过滤器中包装ServletRequest和ServletResponse,如Spring Boot with Hazelcast and Tomcat中所述。