我將需要在Java中實現我自己的HttpSession版本。我發現很少的信息解釋瞭如何實現這樣的壯舉。如何在java中實現自定義http會話?
我想我的問題是 - 無論應用程序服務器的實現如何覆蓋現有的HttpSession? http://java.sun.com/developer/technicalArticles/Servlets/ServletControl/
是否還有其他的方法 -
我沒有穿過質量,而是老讀這有助於我實現我的目標運行?
我將需要在Java中實現我自己的HttpSession版本。我發現很少的信息解釋瞭如何實現這樣的壯舉。如何在java中實現自定義http會話?
我想我的問題是 - 無論應用程序服務器的實現如何覆蓋現有的HttpSession? http://java.sun.com/developer/technicalArticles/Servlets/ServletControl/
是否還有其他的方法 -
我沒有穿過質量,而是老讀這有助於我實現我的目標運行?
創建一個新的類,並實現的HttpSession:
public class MyHttpSession implements javax.servlet.http.HttpSession {
// and implement all the methods
}
聲明:我沒有測試此我自己:
然後寫出具有/ *一個url-pattern的過濾器和擴展HttpServletRequestWrapper
。你的包裝應該返回getSession(boolean)
你自定義的HttpSession
類。 在過濾器中,使用您自己的HttpServletRequestWrapper
。
是的 - 我知道,但如何調用request.getSession()時如何讓應用程序服務器(即Glassfish,WebLogic)返回MyHttpSession? – plymouth5
您正在使用哪個應用程序服務器? – CrackerJack9
今天我使用的是Glassfish 3 – plymouth5
由於HttpSession實現由J2EE容器提供,因此它看起來不像在便攜式方式中可以在不同容器中工作那樣容易實現。
然而,要實現類似的結果,你可以實現一個javax.servlet.Filter接口和javax.servlet.HttpSessionListener並在您的過濾器,包裝材料如在Spring Boot with Hazelcast and Tomcat描述的ServletRequest和ServletResponse的。
其兩種方式。
將原始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中的開頭設置你的過濾器,以確保它在任何其他之前執行。
實現它的第二種方式是向您的Servlet容器提供您的自定義SessionManager。
例如,在Tomcat 7中。
AFAIK,這是不可能的。 JEE規範沒有要求HttpSession實現是可替換的。但主要問題是:你爲什麼想這樣做? –
不確定是否需要知道如何實現它,但請查看http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Session-Tracking。html – eon
你需要做什麼,你認爲你需要實現HttpSession? – CrackerJack9