https://www.it610.com/article/4956002.htm
1. 簡單剖析JSP中session、appliactioon創建過程
在JSP中使用的session、application、pageContext的創建其實是在Servlet容器中實現的,JSP頁面被在Servlet容器中會被轉換爲HttpServlet的一個子類(以tomcat爲例,轉換後的文件存儲在apache-tomcat-*\work\Catalina\[項目IP]\[項目名稱]\org\apache\jsp中)
通過如下代碼截圖可以看出去
Ø application是javax.servlet.ServletContext實例,通過pageContext.getServletContext()獲取
Ø session是javax.servlet.http.HttpSession實例,通過pageContext.getSession()獲取
詳細內容可以通過JSP運行原理以及執行過程源碼分析瞭解
2. Java Web 的×××Listener概述
監聽器是典型的觀察者設計模式的實現
Servlet和spring中我們熟知的listeners包括HttpSessionListener、ServletContextListener、ApplicationListener
Ø HttpSessionListener是對javax.servlet.http.HttpSession(session)的監聽
Ø ServletContextListener是對javax.servlet.ServletContext(application)的監聽
Ø ApplicationListener是對Spring的ApplicationContext的監聽。
這些監聽接口的監聽方法會在它們所監聽的內容狀態發生變化時被調用,這些被監聽的內容(session、application)在服務器啓動時創建,在服務器關閉時銷燬,所以就可以在對應的監聽方法中實現系統的一系列初始化配置動作(後面會舉例介紹)。
這些Listeners接口中都會有對應狀態的監聽方法,例如ServletContextListener
Ø public void contextInitialized(ServletContextEventcontextEvent)在ServletContext創建時被調用
Ø public void contextDestroyed(ServletContextEvent contextEvent)在ServletContext被銷燬時調用
3. ServletContextListener
3.1. 創建監聽器類
【MyServletContextListener.java】
@Component("myServletContextListener") public class MyServletContextListener implements ServletContextListener { private Logger logger = LogManager.getLogger(MyServletContextListener.class); @Override publicvoidcontextInitialized(ServletContextEvent arg0) logger.debug("ServletContext初始化開始"); logger.debug("一系列初始化操作......"); } @Override publicvoidcontextDestroyed(ServletContextEvent arg0) { logger.debug("ServletContext銷燬"); logger.debug("一系列逆初始化操作......"); } }
3.2. 添加監聽器
【web.xml】加一句
<listener>
<listener-class>com.mlq.love.listener.MyServletContextListener</listener-class>
</listener>
3.3. 測試運行
啓動服務器,查看log如下:
3.4. HttpSessionListener簡介
【MyHttpSessionListener.java】
import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class MyHttpSessionListener implements HttpSessionListener { @Override publicvoidsessionCreated(HttpSessionEvent arg0) { } @Override publicvoidsessionDestroyed(HttpSessionEventarg0) { } }
【web.xml】
<listener>
<listener-class>com.mlq.love.listener.MyHttpSessionListener</listener-class>
</listener>
4. AppliactionListener
4.1. Spring啓動過程
Web.xml中配置如下內容
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
查看ContextLoaderListener源碼,發現ContextLoaderListener也實現了ServletContextListener接口,在contextInitialized方法中進行Spring的相關初始化操作:
4.2. 創建(ContextRefreshedEvent事件)監聽器類
4.2.1. ContextRefreshedEvent事件發生過程
Spring框架加載完成後會publishContextRefreshedEvent事件,spring容器的許多初始化工作在ContextLoaderListener中完成,包括初始化applicationContext.xml文件中配置的bean對象、初始化國際化相關的對象(MessageSource)等,當這些步驟執行完後,最後一個就是執行刷新上下文事件,代碼Trace如下
(initWebApplicationContext(event.getServletContext()); public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { try { ... // Initialize message source for this context. initMessageSource(); // Last step: publish corresponding event. finishRefresh(); } catch (BeansException ex) { // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } } } /** * Finish the refresh of this context, invoking the LifecycleProcessor's * onRefresh() method and publishing the * {@link org.springframework.context.event.ContextRefreshedEvent}. */ protected void finishRefresh() { // Initialize lifecycle processor for this context. initLifecycleProcessor(); // Propagate refresh to lifecycle processor first. getLifecycleProcessor().onRefresh(); // Publish the final event. publishEvent(new ContextRefreshedEvent(this)); }
跟進finishRefresh方法可發現publishEvent(newContextRefreshedEvent(this));這行代碼,此處就是刷新上下文的事件
4.2.2. 創建ContextRefreshedEvent事件監聽類
【MyApplicationListener.java】
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; @Component("MyApplicationListener") public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> { Logger logger= LogManager.getLogger(MyApplicationListener.class); @Override public void onApplicationEvent(ContextRefreshedEventevent) { logger.debug("監聽到ContextRefreshedEvent事件"); } }
啓動服務器,log如下:
4.3. 創建(自定義事件)監聽器類
【MyApplicationEvent.java】
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.context.ApplicationEvent; import org.springframework.stereotype.Component; @Component("myApplicationEvent") public class MyApplicationEvent extends ApplicationEvent { Loggerlogger= LogManager.getLogger(MyApplicationEvent.class); private static final long serialVersionUID= 7500024553335407309L; public MyApplicationEvent(Object source) { super(source); } public void testCustomerEvent(){ logger.debug("自定義事件被觸發"); } }
【MyCustomerApplicationListener.java】
public class MyCustomerApplicationListenerimplements ApplicationListener { @Override public void onApplicationEvent(ApplicationEvent event) { if(event instanceof MyApplicationEvent){ MyApplicationEvent myEvent = (MyApplicationEvent)event; myEvent.testCustomerEvent(); } } }