struts 2はSessionListenerを利用してウェブサイトのオンライン人数統計を実現する

2828 ワード

カスタムMySessionListener HttpSessionListenerインタフェース
package com.sessionListener.listener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;


public class MySessionListener implements HttpSessionListener {
	
	private long onlineCount;

	public void sessionCreated(HttpSessionEvent event) {
		// TODO Auto-generated method stub
		this.onlineCount=this.onlineCount+1;
                                // application 
		event.getSession().getServletContext().setAttribute("onlineCount", onlineCount);
	}

	public void sessionDestroyed(HttpSessionEvent event) {
		// TODO Auto-generated method stub
		this.onlineCount=this.onlineCount-1;
		event.getSession().getServletContext().setAttribute("onlineCount", onlineCount);
	}

}

Webでxmlでリスナーを構成する
 
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>	
  
  <!--   -->
  <listener>
  	<listener-class>com.sessionListener.listener.MySessionListener</listener-class>
  </listener>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <filter>
  	<filter-name>struts2</filter-name>
  	<filter-class>
  		org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  	</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>struts2</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping></web-app>

jspページ
 :${application.onlineCount }

 
J 2 EEアプリケーションサーバは、アクセス中の各ユーザに対して、対応するHttpSessionオブジェクトを作成します.ブラウザが初めてWebサイトにアクセスすると、J 2 EEアプリケーションサーバはHttpSessionオブジェクトを新規作成し、HttpSession作成イベントをトリガーします.HttpSessionListenerイベントリスナーが登録されている場合、HttpSessionListenerイベントリスナーのsessionCreatedメソッドが呼び出されます.逆に、このブラウザアクセスがタイムアウトした場合、J 2 EEアプリケーションサーバは対応するHttpSessionオブジェクトを破棄し、HttpSession破棄イベントをトリガーし、登録されたHttpSessionListenerイベントリスナーのsessionDestroyedメソッドを呼び出す.ユーザアクセスの開始と終了に対応して、sessionCreatedメソッドとsessionDestroyedメソッドが実行されることがわかります.これにより,HttpSessionListener実装クラスのsessionCreatedメソッドでカウンタに1を加え,sessionDestroyedメソッドでカウンタを1に減らすだけで,Webサイトのオンライン人数の統計機能を容易に実現できる.