监听器运行机制:当服务器启动时,监听器自动加载(执行构造函数),特定事件发生时,容器自动调用相应监听器中对应事件处理方法。
监听对象:request、session、application
1、监听对象的创建和销毁
request对象:ServletRequestListener(接口)
session对象:HttpSessionListener(接口)
application对象:ServletContextListener(接口)
2、监听对象中属性的变更
request对象:ServletRequestAttributeListener(接口)
session对象:HttpSessionAttributeListener(接口)
application对象:ServletContextAttributeListener(接口)
session对象中属性的变更:
添加:
session.setAttribute(“name”,value);
删除:
session.removeAttribute(“name”);
修改:
session.setAttribute(“a”,value1);
session.setAttribute(“a”,value2);
一、使用监听器统计与显示网站访问用户数目
1、创建类实现接口
public class Listener1 implements HttpSessionListener {
private static int count=0;
@Override
public void sessionCreated(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
count++;
}
@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
}
public static int getCount() {
return count;
}
}
2、web.xml配置
<listener>
<listener-class>com.listeners.Listener</listener-class>
</listener>
3、index.jsp
导包:com.listeners.Listener
网站访问人数:<%=Listener.getCount() %>
二、使用监听器统计与显示网站访问用户列表
1、创建类实现接口
public class Listener1 implements HttpSessionAttributeListener {
private static List<String> list=new ArrayList<String>();
@Override
public void attributeAdded(HttpSessionBindingEvent arg0) {
// TODO Auto-generated method stub
list.add((String) arg0.getSession().getAttribute("user"));
}
@Override
public void attributeRemoved(HttpSessionBindingEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void attributeReplaced(HttpSessionBindingEvent arg0) {
// TODO Auto-generated method stub
}
public static List<String> getList() {
return list;
}
2、web.xml配置
<listener>
<listener-class>com.listeners.Listener1</listener-class>
</listener>
3、servlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session=request.getSession();
session.setAttribute("user", request.getParameter("user"));
response.sendRedirect("../main.jsp");
}
4、index.jsp
<form action="servlet/LoginServlet" method="post">
<input type="text" name="user">
<input type="submit" value="load">
</form>
main.jsp
访问的用户列表为:<br>
<c:forEach items="<%=Listener1.getList() %>" var="list" varStatus="id">
第${id.count}个用户:${list}<br>
</c:forEach>