---
title: "HttpSessionListener"
author: "ghsea"
date: "2007-08-11T10:37:14Z"
tags: []
slug: "httpsessionlistener"
draft: false
lastmod: "2007-08-11T10:37:14Z"
id: 111175
url: "https://ghsea.iteye.com/blog/111175"
---

这个接口主要是用来监控session的创建和消毁的，它有两个方法

1. public void sessionCreated(HttpSessionEvent se)
2. public void sessionDestroyed(HttpSessionEvent se)

我们要实现监控session的功能，需要实现这个接口，然后在web .xml中配置一个Listener.

01. /\**
02. \* 编写以下SessionCounter.java
03. \* 并编译为SessiionCounter.class
04. \* 然后放到你的网站的classpath的
05. \* SessionCount(自己建立此目录)下面
06. \*/
07. 1\.
08. 2\. package SessionCount;
09. 3\. import javax.servlet.\*;
10. 4\. import javax.servlet.http.\*;
11. 5\.
12. 6\. public class SessionCounter implements HttpSessionListener {
13. 7\.
14. 8\. private static int activeSessions = 0;
15. 9\.
16. 10\. public void sessionCreated(HttpSessionEvent se) {
17. 11\. activeSessions++;
18. 12\. }
19. 13\.
20. 14\. public void sessionDestroyed(HttpSessionEvent se) {
21. 15\. if(activeSessions &gt; 0)
22. 16\. activeSessions--;
23. 17\. }
24. 18\.
25. 19\. public static int getActiveSessions() {
26. 20\. return activeSessions;
27. 21\. }
28. 22\. }

<!--THE END-->

1. &lt;%@ page import="SessionCount.SessionCounter" %&gt;
2. 在线：&lt;%= SessionCounter.getActiveSessions() %&gt;

<!--THE END-->

01. xml version="1.0" encoding="ISO-8859-1"?&gt;
02. PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
03. "http://java.sun.com/j2ee/dtds/web-app\_2.3.dtd"&gt;
04. &lt;web-app&gt;
05. &lt;listener&gt;
06. &lt;listener-class&gt;
07. SessionCount.SessionCounter
08. listener-class&gt;
09. listener&gt;
10. web-app&gt;