freestar
freestar

Reputation: 448

Java / JSP / Sessions

I have implemented a SessionListener to count sessions on my web app. I have setMaxInterval(60) and my problem is the following: if the session expires the session counter is set to 0 and if i start to navigate on the web page again, the session counter is not incremented. Why not?

public class SessionListener implements HttpSessionListener {

static int counter = 0;

public void sessionCreated(HttpSessionEvent e)
{
    HttpSession s = e.getSession();

    s.setMaxInactiveInterval(60);

    counter++;

    synchronized(s.getServletContext())
    {
        s.getServletContext().setAttribute("allConnections", counter);

    }
}

public void sessionDestroyed(HttpSessionEvent e)
{
    HttpSession s = e.getSession();

    counter--;

    synchronized(s.getServletContext())
    {
        s.getServletContext().setAttribute("allConnections", counter);
    }


}

Then, each JSP display the counter variable on the frontend by application.getAttribute("allConnections")

Upvotes: 0

Views: 422

Answers (2)

Andres
Andres

Reputation: 10717

Loading a JSP may or may not create a session depending on the value of this directive:

<%@ page session="false" %>

Upvotes: 0

ernest_k
ernest_k

Reputation: 45319

That is because the counter variable in an object that's session-specific (you're storing it in the session object as an attribute or something similar)

Your solutions (you choose): - Put the counter in the Application context/scope (or in a singleton object that's on that scope) - Make the counter variable static (if it is in your listener)

EDIT after question update The session attribute is being set once, when the session is created. This means that only the initial value (the one applicable when the session was created) will ever be shown for any given session.

The value must be read on each request that renders the page displaying the counter. You have a few options for this:

  • The JSP/servlet can read the value directly, if you can provide a static getter in the SessionListener class
  • Better: you could add a filter that sets the updated counter as an attribute in the request scope. You'd just have to make sure that the filter executes on each request (jsp, servlet, etc) that displays the counter.

Upvotes: 1

Related Questions