我正在使用上下文來共享登錄會話。我使用setAttibute
功能。 我知道HttpSession
具有設置最大超時時間的屬性。是否可以設置ServletContext超時?
是否可以使用類似的方式設置上下文屬性?
ServletContext context = httpservlet.getServletContext();
context.setAttribute("currentSessionUser", username);
感謝
我正在使用上下文來共享登錄會話。我使用setAttibute
功能。 我知道HttpSession
具有設置最大超時時間的屬性。是否可以設置ServletContext超時?
是否可以使用類似的方式設置上下文屬性?
ServletContext context = httpservlet.getServletContext();
context.setAttribute("currentSessionUser", username);
感謝
不要那樣做。上下文在整個應用程序範圍內,並且當多個用戶瀏覽您的網站時,您會得到非常意外的結果。
您需要設置該屬性currentSessionUser在HttpSession中和它是相關的,而不是ServletContext中,ServletContext的將被摧毀,當任何重載情況(JAR部署)。
request.getSession(false).setAttribute("currentSessionUser", username);
您可以爲您的應用程序定義會話超時屬性。寫在你的web.xml:
<session-config>
<session-timeout>30</session-timeout>
</session-config>
我這樣做:
把一個物體在兩個ServletContext中和的HttpSession:
String username = getUsername();
TheObject theObject = null;
if(session.getServletContext().getAttribute(THE_SESSION_KEY + "_" + theObject.getCurrentUsername()) == null) {
theObject = new TheObject(username);
session.setAttribute(THE_SESSION_KEY, theObject);
session.getServletContext().setAttribute(THE_SESSION_KEY + "_" + username, theObject);
}
else {
theObject = (TheObject)session.getServletContext().getAttribute(THE_SESSION_KEY + "_" + theObject.getCurrentUsername());
}
創建一個會話事件偵聽器
public void sessionDestroyed(HttpSessionEvent arg0) {
if(arg0.getSession().getAttribute(THE_SESSION_KEY) != null) {
TheObject theObject = (TheObject)arg0.getSession().getAttribute(THE_SESSION_KEY);
arg0.getSession().getServletContext().removeAttribute(THE_SESSION_KEY + "_" + theObject.getCurrentUsername());
}
}
每個Web應用程序都有一個「ServeltContext」實例。爲什麼你使用它來存儲用戶信息? – 2011-02-16 08:44:13