Search code examples
javasessionservletsservlet-listeners

Modify an attribute of ServletContext from valueUnbound(HttpSessionBindingEvent event) method


I need to change an attribute in ServletContext when a User Session is expired.

How suggest here how-to-call-a-method-before-the-session-object-is-destroyed, I've implemented the method valueUnbound(HttpSessionBindingEvent event) in my java class, who allow to access to Session object before it's destroyed using event reference.

Inside this method I need to change a value in array that is attribute in ServletContext. How can I do?

public class myClass implements HttpSessionBindingListener {

@Override
public void valueUnbound(HttpSessionBindingEvent event) {
    int userid = Integer.valueOf((Integer) event.getSession().getAttribute("IDplayer"));
    boolean[] id_used = (boolean[]) getServletContext().getAttribute("id_used"); 
}

The problem is that getServletContext().getAttribute() is not founded, also if I included the "import javax.servlet.*".

How can I access to ServletContext attribute from a method called before the session is closed?


Solution

  • Access it via HttpSessionBindingEvent. Use this:

     event.getSession().getServletContext().getAttribute("id_used");