1. 程式人生 > >Listener、Filter、Servlet 初始化

Listener、Filter、Servlet 初始化

  • listener、Filter、Servlet都有一個初始化的過程
  • 那麼它們的初始化順序是: listener > Filter > Servlet;
  • servlet初始化
    import java.io.IOException;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    
    public class TestFilter implements Filter{
     
     
      public void init(FilterConfig filterConfig) throws ServletException { 
             System.out.println("Filter 初始化。。。"); 
         } 
         public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 
             System.out.println("doFilter 。。。"); 
             chain.doFilter(request, response); 
         } 
         public void destroy() { 
             System.out.println("Filter 銷燬。。。"); 
         } 
    }


  • filter初始化
    import java.io.IOException;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    
    public class TestFilter implements Filter{
     
     
      public void init(FilterConfig filterConfig) throws ServletException { 
             System.out.println("Filter 初始化。。。"); 
         } 
         public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 
             System.out.println("doFilter 。。。"); 
             chain.doFilter(request, response); 
         } 
         public void destroy() { 
             System.out.println("Filter 銷燬。。。"); 
         } 
    }
  • Listener 初始化
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;
    
    public class TestListener implements ServletContextListener{
      public void contextInitialized(ServletContextEvent arg0) { 
             System.out.println("Listener 初始化。。。"); 
         } 
         public void contextDestroyed(ServletContextEvent arg0) { 
             System.out.println("Listener 銷燬。。。"); 
         } 
    }

    web.xml
    <servlet> 
            <servlet-name>s</servlet-name> 
            <servlet-class>com.zm.test.TestServlet</servlet-class> 
        </servlet> 
        <servlet-mapping> 
            <servlet-name>s</servlet-name> 
            <url-pattern>/login</url-pattern> 
        </servlet-mapping> 
        <filter> 
            <filter-name>f</filter-name> 
            <filter-class>com.zm.test.TestFilter</filter-class> 
        </filter> 
        <filter-mapping> 
            <filter-name>f</filter-name> 
            <url-pattern>/*</url-pattern> 
        </filter-mapping> 
        <listener> 
            <listener-class>com.zm.test.TestListener</listener-class> 
        </listener>