[英]Is it possible to set ServletContext timeout?
我正在使用上下文來共享登錄會話。 我使用setAttibute
函數。 我知道HttpSession
具有設置最大超時時間的屬性。
是否可以以類似的方式設置上下文屬性?
ServletContext context = httpservlet.getServletContext();
context.setAttribute("currentSessionUser", username);
謝謝
不要那樣做。 上下文是應用程序范圍的,當多個用戶瀏覽您的站點時,您將獲得非常意外的結果。
我喜歡這個:
在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()); } }
你需要在HttpSession中設置屬性currentSessionUser並且它是相關的,而不是ServletContext,當任何重載發生時(JAR部署),ServletContext將被破壞。
request.getSession(false).setAttribute("currentSessionUser", username);
您可以為應用程序定義session-timeout屬性。 寫在你的web.xml中:
<session-config>
<session-timeout>30</session-timeout>
</session-config>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.