Web应用中监听者的通知顺序按照DD中的定义顺序:
XML:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>TestBootWeb</display-name> <servlet> <servlet-name>TestServlet1</servlet-name> <servlet-class>com.stono.servlet.listenerorder.TestServlet1</servlet-class> </servlet> <servlet-mapping> <servlet-name>TestServlet1</servlet-name> <url-pattern>/a.do</url-pattern> </servlet-mapping> <listener> <listener-class>com.stono.servlet.listeners.MyHttpSessionListener2</listener-class> <listener-class>com.stono.servlet.listeners.MyHttpSessionAttributeListener</listener-class> <listener-class>com.stono.servlet.listeners.MyHttpSessionListener</listener-class> </listener> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
Listener:
package com.stono.servlet.listeners; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class MyHttpSessionListener implements HttpSessionListener { @Override /* 必须调用一下session.getAttributeNames();才可以激活这个事件; */ public void sessionCreated(HttpSessionEvent arg0) { System.out.println("com.stono.servlet.listeners.MyHttpSessionListener.sessionCreated(HttpSessionEvent)"); } @Override /* 调用session.invalidate()的时候激活这个事件; */ public void sessionDestroyed(HttpSessionEvent arg0) { System.out.println("com.stono.servlet.listeners.MyHttpSessionListener.sessionDestroyed(HttpSessionEvent)"); } }
package com.stono.servlet.listeners; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class MyHttpSessionListener2 implements HttpSessionListener { @Override public void sessionCreated(HttpSessionEvent arg0) { System.out.println("com.stono.servlet.listeners.MyHttpSessionListener2.sessionCreated(HttpSessionEvent)"); } @Override public void sessionDestroyed(HttpSessionEvent arg0) { System.out.println("com.stono.servlet.listeners.MyHttpSessionListener2.sessionDestroyed(HttpSessionEvent)"); } }
Servlet:
package com.stono.servlet.listenerorder; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class TestServlet1 extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); session.setAttribute("a", "a"); PrintWriter writer = resp.getWriter(); writer.println("this is from com.stono.servlet.listenerorder.TestServlet1"); } }
时间: 2024-10-25 13:51:12