用listener,filter,servlet在web應用啓動時進行初始化

當web應用啓動時,有三種方式能夠進行初始化工做。
初始化順序是 <context-param> - <listener> - <filter> - <servlet>.
 

1. listener

    (1) 實現javax.servlet.ServletContextListener接口.       
         
@Override 
public void contextInitialized(ServletContextEvent event) { 
}

    (2) web.xml  
        
<listener>
   <listener-class>org.blueleek.Listener</listener-class>
</listener>

       
 

    (3) depends on the order of your <listener> elements in the web.xml java

 

2. filter

   (1)實現javax.servlet.Filter接口.  
    
@Override 
public void init(FilterConfig config) throws ServletException { 
}

   (2)web.xml   
<filter>
      <filter-name>ofilter</filter-name>
      <filter-class>order.OFilter</filter-class>
</filter>
<filter-mapping>
      <filter-name>ofilter</filter-name>
      <url-pattern>/*</url-pattern>
</filter-mapping>

   (3) The container uses the <filter-mapping> declarations to decide which filters to apply to a request,and in what order.              web

3. servlet

    (1)繼承javax.servlet.http.HttpServlet類.  
   
@Override 
public void init() throws ServletException { 
 super.init(); 
}
   (2)web.xml         
<servlet>
      <servlet-name>oservlet</servlet-name>
      <servlet-class>org.blueleek..OServlet</servlet-class>
      <load-on-startup></load-on-startup>
</servlet>

    (3) The load-on-startup element indicates that this servlet should be loaded (instantiated and have its init() called) on the startup of the web application. The optional contents of these element must be an integer indicating the order in which the servlet should be loaded. If the value is a negative integer, or the element is not present, the container is free to load the servlet whenever it chooses. If the value is a positive integer or 0, the container must load and initialize the servlet as the application is deployed. The container must guarantee that servlets marked with lower integers are loaded before servlets marked with higher integers. The container may choose the order of loading of servlets with the same load-on-start-up value.app

 

結論來自: http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd 以及本身動手實驗.ide

相關文章
相關標籤/搜索