ServletContextListener的做用

ServletContextListener是對ServeltContext的一個監聽.servelt容器啓動,serveltContextListener就會調用contextInitialized方法.在方法裏面調用event.getServletContext()能夠獲取ServletContext,ServeltContext是一個上下文對象,他的數據供全部的應用程序共享,進行一些業務的初始化servelt容器關閉,serveltContextListener就會調用contextDestroyed.html

  實際上ServeltContextListener是生成ServeltContext對象以後調用的.生成ServeltContext對象以後,這些代碼在咱們業務實現以前就寫好,它怎麼知道咱們生成類的名字.實際上它並不須要知道咱們的類名,類裏面有是方法.他們提供一個規範,就一個接口,ServeltContextListner,只要繼承這個接口就必須實現這個方法.而後這個類在web.xml中Listener節點配置好.Servelt容器先解析web.xml,獲取Listener的值.經過反射生成對象放進緩存.而後建立ServeltContext對象和ServletContextEvent對象.而後在調用ServletContextListener的contextInitialized方法,而後方法能夠把用戶的業務需求寫進去.struts和spring框架就是相似這樣的實現,咱們之後寫一些框架也能夠在用.java

java代碼web

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package  com.chen;
 
import  javax.servlet.ServletContext;
import  javax.servlet.ServletContextEvent;
import  javax.servlet.ServletContextListener;
 
public  class  MyServletContextListener  implements  ServletContextListener{
 
     @Override
     public  void  contextDestroyed(ServletContextEvent arg0) {
         System.out.println( "destroyed" );
     }
 
     @Override
     public  void  contextInitialized(ServletContextEvent event) {
         System.out.println( "initialized" );
         event.getServletContext().setAttribute( "user" "admin" );
         
     }
 
}<br>

  xml配置spring

1
2
3
4
5
6
7
8
9
10
11
12
<?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"  xmlns:web= "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  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>oa</display-name>
 
   <listener>
     <listener- class >com.chen.MyServletContextListener</listener- class >
   </listener>
 
   <welcome-file-list>
     <welcome-file>index.html</welcome-file>
   </welcome-file-list>
</web-app>
相關文章
相關標籤/搜索