既然是监听器,他监听什么呢?
主要包括:
看下api,主要针对下面几个的监听,
ServletContent 就是jsp中的application;
HttpSession,jsp中的session;
HttpServletRequest,jsp中的request.
先看一下ServletContent吧,他是通过两个接口实现监听的:
Interface ServletContextAttributeListener,主要是针对
application的属性进行监听,看里面的方法:
public void attributeAdded(ServletContextAttributeEvent
scab),属性增加
public void attributeRemoved(ServletContextAttributeEvent
scab),属性移除
public void attributeReplaced
(ServletContextAttributeEvent scab),属性替换
和
Interface ServletContextListener,主要是对application的创
建与销毁进行监听,从里面的方法可以看出:
public void contextInitialized(ServletContextEvent sce),
public void contextDestroyed(ServletContextEvent sce)
一个是初始化,一个是销毁。
关于Session等, 也是类似查看下api吧。
不在详细说明了。
下面以一个实例说明servlet监听器的具体使用吧。
用与统计在线人员列表:
先看下大体框架:
package com.zzc;
public class ShowPerson implements
ServletContentListener,HttpSessionListener,HttpSessionAtt
ributer{
//对应接口的方法都要写上。
当然实现每个接口都是有用处的,
ServletContentListener不是相当于对application监听吗,这里
用于记录在线用户。
HttpSessionListener,把用户存入session .
HttpSessionAttributer,对在线人员属性的监听。
}
具体的写下,当然方法等都还是在api上复制下来的。
package com.zzc;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class ShowPerson implements
ServletContextListener,HttpSessionListener,HttpSessionAtt
ributeListener{
private ServletContext application = null;
public void contextInitialized
(ServletContextEvent sce){
this.application = sce.getServletContext
();
this.application.setAttribute
("allusers",new ArrayList()); //初始化存放用户的一个容器,
采用数组存放
}
public void contextDestroyed(ServletContextEvent
sce){}
public void sessionCreated(HttpSessionEvent se){}
public void sessionDestroyed(HttpSessionEvent
se){//删除离开的用户
List l = (List)
this.application.getAttribute("allusers");
String value =(String) se.getSession
().getAttribute("uname");
l.remove(value);
this.application.setAttribute
("allusers",l);
}
public void attributeAdded
(HttpSessionBindingEvent se){
/*当一个用户登陆成功时,存放进application*/
List l = (List)
this.application.getAttribute("allusers");
l.add(se.getValue());
this.application.setAttribute
("allusers",l);
}
public void attributeRemoved
(HttpSessionBindingEvent se){}
public void attributeReplaced
(HttpSessionBindingEvent se){}
}
一个简单的显示在线用户的监听器完成了,不要忘记配置下xml.
<listener>
<listener-class>com.zzc.ShowPerson</listener-class>
</listener>
和过滤器不大一样,要简单点。
怎么在具体jsp文件中使用它呢?
。首先要有个action,用于用户登陆,在着简单方便光记个用户名。
还要用个循环显示登陆用户。
具体 jsp 文件差不多就出来了。
<%@ page contentType="text/html;charset=utf-8"%>
<%@ page import="java.util.*"%>
<%
if(request.getParameter("name")!=null)
{
session.setAttribute("uname",request.getParameter("uname")) ;
}
%>
<!-- 传递参数到当前页面 -->
<form action="?" method="post">
用户名:
<input type="text" name="uname">
<input type="submit" value="登陆">
<a href="#">注销</a> //可以在另一个页面调用 session.invalidate();
</form>
<!-- 向session接收输入的用户名 -->
<h2>在线人员</h2>
<hr />
<%
List l = (List)application.getAttribute("allusers") ;
Iterator it = l.iterator() ;
while(it.hasNext())
{
%>
<li><%=it.next()%>
<%
}
%>
到这框架差不多就完成了,然后可以对其自己修改或增加新的功能了。