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.........."); } }
推荐阅读
-
Servlet、Filter、Listener执行的先后顺序 博客分类: J2EE
-
Tomcat7下Filter执行顺序小验证 博客分类: java;tomcat7;servlet tomcatservletjava
-
Tomcat7下Filter执行顺序小验证 博客分类: java;tomcat7;servlet tomcatservletjava
-
Servlet,Listener和Filter如何获取ServletContext(既application) 博客分类: java语言相关 ServletWebSpring生活
-
Servlet,Listener和Filter如何获取ServletContext(既application) 博客分类: java语言相关 ServletWebSpring生活