I am using context to share login sessions. I use setAttibute
function.
I know HttpSession
has the property of setting the maximum timeout time.
Is it possible to se开发者_运维问答t context attribute a similar way?
ServletContext context = httpservlet.getServletContext();
context.setAttribute("currentSessionUser", username);
Thanks
Don't do that. the context is application-wide, and you will get very unexpected results when more than one user is browsing your site.
You need to set the attribute currentSessionUser in HttpSession and it is relevant ,rather than ServletContext, ServletContext will get destroyed ,when any reload happens(JAR Deployment).
request.getSession(false).setAttribute("currentSessionUser", username);
You can define session-timeout attribute for your application. Write in your web.xml:
<session-config>
<session-timeout>30</session-timeout>
</session-config>
I do like this:
put an object in both ServletContext and 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()); }
Create a session event listener
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()); } }
精彩评论