leon
leon

Reputation: 10395

Is it possible to set ServletContext timeout?

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 set context attribute a similar way?

ServletContext context = httpservlet.getServletContext();


context.setAttribute("currentSessionUser", username);

Thanks

Upvotes: 0

Views: 2269

Answers (4)

Jasonw
Jasonw

Reputation: 98

I do like this:

  1. 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());
    }
    
  2. 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());
        }
    }

Upvotes: 0

yname
yname

Reputation: 2255

You can define session-timeout attribute for your application. Write in your web.xml:

<session-config>
   <session-timeout>30</session-timeout>
</session-config>

Upvotes: 0

Dead Programmer
Dead Programmer

Reputation: 12585

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);

Upvotes: 0

Bozho
Bozho

Reputation: 597324

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.

Upvotes: 2

Related Questions