欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Servlet、Filter、Listener执行的先后顺序 博客分类: J2EE  

程序员文章站 2024-03-23 16:08:04
...
Listener在web容器中优先于Fiter执行,即在Filter之前执行
Fiter在web容器中优先于Servlet执行,即在Servlet之前执行
ServletContextListener最先执行,容器一启动便执行它的contextInitialized方法。
示例代码如下:
 
package com.anxiesoft.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class MyListener implements HttpSessionListener, ServletContextListener,
  HttpSessionBindingListener {
 private static Map hUserName = new HashMap();

 @Override
 public void sessionCreated(HttpSessionEvent arg0) {
  System.out.println(".....sessionCreated.......");
 }

 @Override
 public void sessionDestroyed(HttpSessionEvent arg0) {
  System.out.println(".....sessionDestroyed.......");
  hUserName.remove(arg0.getSession().getId());
 }

 public static boolean isOnline(HttpSession session) {
  boolean flag = true;
  if (hUserName.containsKey(session.getId())) {
   flag = true;
  } else {
   flag = false;
  }
  return flag;
 }

 public static boolean isAlreadyEnter(HttpSession session, String sUserName) {
  boolean flag = false;
  if (hUserName.containsValue(sUserName)) {
   flag = true;
   // 遍历原来的hUserName,删除原用户对应的SessionId(即删除原来的sessionId和Username)
   Iterator iter = hUserName.entrySet().iterator();
   while (iter.hasNext()) {
    Map.Entry entry = (Map.Entry) iter.next();
    Object key = entry.getKey();
    Object value = entry.getValue();
    if (((String) value).equals(sUserName)) {
     hUserName.remove(key);
    }
   }
   hUserName.put(session.getId(), sUserName);
   System.out.println("hUserName = " + hUserName);
  } else {
   flag = false;
   hUserName.put(session.getId(), sUserName);
   System.out.println("hUserName = " + hUserName);
  }
  return flag;
 }

 @Override
 public void contextDestroyed(ServletContextEvent arg0) {
  System.out.println("......contextDestroyed..........");
 }

 @Override
 public void contextInitialized(ServletContextEvent arg0) {
  System.out.println("......contextInitialized..........");
 }

 @Override
 public void valueBound(HttpSessionBindingEvent arg0) {
  System.out.println("......valueBound..........");
 }

 @Override
 public void valueUnbound(HttpSessionBindingEvent arg0) {
  System.out.println("......valueUnbound..........");
 }
}