servlet对java的重要性_浅谈Servlet技术中的Listener起到的作用

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

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

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

com.xxx.xxx.ImplementListener

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

常用的监听接口:

监听对象

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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值