码迷,mamicode.com
首页 > 其他好文 > 详细

Servlet监听器Listener

时间:2014-07-25 11:34:51      阅读:292      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   java   color   使用   os   

Listener实在servlet2.3中加入的,主要用于对Session,request,context等进行监控。

使用Listener需要实现响应的接口。触发Listener事件的时候,tomcat会自动调用Listener的方法。

web.xml中配置标签,一般要配置在<servlet>标签前面,可配置多个,同一种类型也可配置多个

<listener>   

<listener-class>com.xxx.xxx.ImplementListener</listener-class> 

  </listener> 

servlet2.5的规范中共有8Listener,分别监听sessioncontextrequest等的创建和销毁,属性变化等。

        

常用的监听接口: 

监听对象

HttpSessionListener :监听HttpSession的操作,监听session的创建和销毁。 可用于收集在线着信息

ServletRequestListener:监听request的创建和销毁。

ServletContextListener:监听context的创建和销毁。  启动时获取web.xml里配置的初始化参数

监听对象的属性

HttpSessionAttributeListener 

ServletContextAttributeListener 

ServletRequestAttributeListener 

监听session内的对象

HttpSessionBindingListener:对象被放到session里执行valueBound(),对象移除时执行valueUnbound()。对象必须实现该lisener接口。

HttpSessionActivationListener:服务器关闭时,会将session里的内容保存到硬盘上,这个过程叫做钝化。服务器重启时,会将session内容从硬盘上重新加载。

 

Listener应用实例

利用HttpSessionListener统计最多在线用户人数

 

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class HttpSessionListenerImpl implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent event) {
        ServletContext app = event.getSession().getServletContext();
        int count = Integer.parseInt(app.getAttribute("onLineCount").toString());
        count++;
        app.setAttribute("onLineCount", count);
        int maxOnLineCount = Integer.parseInt(app.getAttribute("maxOnLineCount").toString());
        if (count > maxOnLineCount) {
            //记录最多人数是多少
            app.setAttribute("maxOnLineCount", count);
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //记录在那个时刻达到上限
            app.setAttribute("date", df.format(new Date()));
        }
    }
    //session注销、超时时候调用,停止tomcat不会调用
    public void sessionDestroyed(HttpSessionEvent event) {
        ServletContext app = event.getSession().getServletContext();
        int count = Integer.parseInt(app.getAttribute("onLineCount").toString());
        count--;
        app.setAttribute("onLineCount", count);    
        
    }
}

 

参考资料:

http://www.cnblogs.com/hellojava/archive/2012/12/26/2833840.html


本文出自 “风云海滩” 博客,请务必保留此出处http://3950566.blog.51cto.com/3940566/1529902

Servlet监听器Listener,布布扣,bubuko.com

Servlet监听器Listener

标签:des   style   blog   http   java   color   使用   os   

原文地址:http://3950566.blog.51cto.com/3940566/1529902

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!