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>
相关文章
相关标签/搜索