【发布时间】:2016-05-25 14:10:54
【问题描述】:
我已经实现了SessionListener 来计算我的网络应用程序上的会话数。我有setMaxInterval(60),我的问题如下:如果会话过期,则会话计数器设置为 0,并且如果我再次开始在网页上导航,则会话计数器不会增加。为什么不呢?
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);
}
}
然后,每个JSP在前端通过application.getAttribute("allConnections")显示计数器变量
【问题讨论】:
-
显示代码中的 sn-ps 将大大有助于更准确地回答。
-
您的原始代码对我有用。我刚刚添加了调试行以打印到控制台。我用两种方法打印了计数器的值。我还将非活动间隔更改为 6 秒。这样你就可以只看控制台并看到计数器快速上升和下降。我在桌面上使用了三种不同的浏览器(IE、Chrome 和 Firefox)。你的代码没问题。
-
我使用单个浏览器以另一种方式测试了您的代码。它工作正常。我在桌面上创建了 JSP 的快捷方式。我浏览到该页面,然后快速关闭浏览器。我一遍又一遍地做同样的事情。
-
很奇怪,现在它显示空值而不是 0 或 1...
-
在 JSP 中,您应该使用:Session count is ${allConnections}