首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

HttpSessionListener用法 监听对话使用数量

2012-11-01 
HttpSessionListener用法 监听会话使用数量HttpSessionListener接口是一个可监听java Web项目中Session的

HttpSessionListener用法 监听会话使用数量
HttpSessionListener接口是一个可监听java Web项目中Session的创建和消毁状态。
在理解这个接口之前,先提出一个问题,就是假设我的web应用上想知道到底有多少用户在使用?
具体使用,请看如下代码:

package demo.listener;import javax.servlet.ServletContext;import javax.servlet.http.HttpSessionEvent;import javax.servlet.http.HttpSessionListener;public class SessionCounter implements HttpSessionListener {    public void sessionCreated(HttpSessionEvent event) {        ServletContext ctx = event.getSession( ).getServletContext( );        Integer numSessions = (Integer) ctx.getAttribute("numSessions");        if (numSessions == null) {            numSessions = new Integer(1);        }        else {            int count = numSessions.intValue( );            numSessions = new Integer(count + 1);        }        ctx.setAttribute("numSessions", numSessions);    }    public void sessionDestroyed(HttpSessionEvent event) {        ServletContext ctx = event.getSession( ).getServletContext( );        Integer numSessions = (Integer) ctx.getAttribute("numSessions");        if (numSessions == null) {            numSessions = new Integer(0);        }        else {            int count = numSessions.intValue( );            numSessions = new Integer(count - 1);        }        ctx.setAttribute("numSessions", numSessions);    }}


在这个解决方案中,任何一个Session被创建或者销毁时,都会通知SessionCounter 这个类,当然通知的原因是必须在web.xml文件中做相关的配置工作。如下面的配置代码:

<?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE web-app PUBLIC    "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"    "http://java.sun.com/dtd/web-app_2_3.dtd">    <web-app>  <display-name>Struts Examples</display-name>    <listener>      <listener-class>demo.listener.SessionCounter      </listener-class>  </listener>







热点排行