// 程序名称:示例14-9 : EncodingFilter .java
// 程序目的:学习使用监听器
// ==============================================================
import javax.servlet.http.*;
import javax.servlet.*;
public class OnLineCountListener implements HttpSessionListener,
ServletContextListener,ServletContextAttributeListener
{
private int count;
private ServletContext context = null;
public OnLineCountListener()
{
count=0;
//setContext();
}
//创建一个session时激发
public void sessionCreated(HttpSessionEvent se)
{
count++;
setContext(se);
}
//当一个session失效时激发
public void sessionDestroyed(HttpSessionEvent se)
{
count--;
setContext(se);
}
//设置context的属性,它将激发attributeReplaced或attributeAdded方法
public void setContext(HttpSessionEvent se)
{
se.getSession().getServletContext().
etAttribute("onLine",new Integer(count));
}
//增加一个新的属性时激发
public void attributeAdded(ServletContextAttributeEvent event) {
log("attributeAdded('" + event.getName() + "', '" +
event.getValue() + "')");
}
//删除一个新的属性时激发
public void attributeRemoved(ServletContextAttributeEvent event) {
log("attributeRemoved('" + event.getName() + "', '" +
event.getValue() + "')");
}
//属性被替代时激发
public void attributeReplaced(ServletContextAttributeEvent event) {
log("attributeReplaced('" + event.getName() + "', '" +
event.getValue() + "')");
}
//context删除时激发
public void contextDestroyed(ServletContextEvent event) {
log("contextDestroyed()");
this.context = null;
}
//context初始化时激发
public void contextInitialized(ServletContextEvent event) {
this.context = event.getServletContext();
log("contextInitialized()");
}
private void log(String message) {
System.out.println("ContextListener: " + message);
}
}
在OnLineCountListener里,用count代表当前在线的人数,OnLineCountListener将在Web服务器启动时自动执行。当
为了使监听器生效,需要在web.xml里进行配置,如下所示:
<listener-class>OnLineCountListener
</listener-class>
</listener>
目前在线人数:
<font color=red><%=getServletContext().getAttribute("onLine")%></font><br>
退出会话:
<form action="exit.jsp" method=post>
<input type=submit value="exit">
</form>
getServletContext().getAttribute("onLine")获得了count的具体值。客户端调用
<%session.invalidate() ;%>
【运行程序】
web.xml做好以上的配置,把OnLineCountListener放在WEB-INF/class目录下,启动Web服务器,在浏览器里输入以下URL测试就可以了