有两种方式。
“包裹”原来的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.