分享

How to count active sessions in your web application?

 真爱图书 2012-12-23

If you have unique users on a Web site and need to know who they are or need to get specific information to them, such as search results, then you should be using sessions. A session is a sort of temporary unique connection between the server and client by which the server keeps track of that specific user. That unique session can be used by web applications to display this content to one user and that content to the other user.

How to count active sessions in your web application? For a servlet container or application server which supports Serlvet 2.3 speicification, we can have our session count class implementing HttpSessionListener interface. Our listener object will be called every time a session is created or destroyed by the server. You can find more information about HttpSessionListener at When do I use HttpSessionListener?.

For example, we have MySessionCounter.java that implements HttpSessionListener interface. We implement sessionCreated() and sessionDestroyed() methods, the sessionCreated() method will be called by the server every time a session is created and the sessionDestroyed() method will be called every time a session is invalidated or destroyed.

package com.xyzws.web.utils;

import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;

public class MySessionCounter implements HttpSessionListener {

private static int activeSessions = 0;

public void sessionCreated(HttpSessionEvent se) {
activeSessions++;
}

public void sessionDestroyed(HttpSessionEvent se) {
if(activeSessions > 0)
activeSessions--;
}

public static int getActiveSessions() {
return activeSessions;
}

}

Compile this code and drop the class file in the /WEB-INF/classes/com/xyzws/web/utils/ folder of your web application.

To receive notification events, the implementation class MySessionCounter must be configured in the deployment descriptor for the web application. add <listener> section into your /WEB-INF/web.xml file:

  <!-- Listeners -->
<listener>
<listener-class>com.xyzws.web.utils.MySessionCounter</listener-class>
</listener>

For example, the following JSP code shows the total active session:

<%@ page import="com.xyzws.utils.MySessionCounter"%>
<html>
...
Active Sessions : <%= MySessionCounter.getActiveSessions() %>
...
</html>

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多