Java徹底 - WEB容器的偵聽具體解釋 ServletContextListener

weixin_34377065發表於2015-07-04

WEB容器的偵聽器ServletContextListener主要用於監測容器啟動和 當破壞需要做一些操作,聽眾將能夠使用此做。

ServletContextListener在Spring開始,然後再開始。


們實現一個簡單的監聽器,須要繼承介面ServletContextListener:

 * 一個測試的監聽器樣例
 * @author zhuli
 * @date 2014-7-26
 */
public class TestContextLister implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("==============================容器裝載");

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("==============================容器銷燬");
    }

}

ServletContextListener 實現兩個介面,一個是容器啟動的時候,一個是容器銷燬的時候:

public interface ServletContextListener extends EventListener {
	/**
	 ** Notification that the web application initialization
	 ** process is starting.
	 ** All ServletContextListeners are notified of context
	 ** initialization before any filter or servlet in the web
	 ** application is initialized.
	 */

    public void contextInitialized ( ServletContextEvent sce );

	/**
	 ** Notification that the servlet context is about to be shut down.
	 ** All servlets and filters have been destroy()ed before any
	 ** ServletContextListeners are notified of context
	 ** destruction.
	 */
    public void contextDestroyed ( ServletContextEvent sce );
}

在web.xml中的配置:

	<listener>
		<listener-class>com.xxx.controller.web.TestContextLister</listener-class>
	</listener>

容器啟動後,會在容器啟動的日誌中看到:

==============================容器裝載
2014-07-26 08:54:01.302:INFO:/:Initializing Spring FrameworkServlet 'apiServlet'



版權宣告:本文部落格原創文章,部落格,未經同意,不得轉載。

相關文章