Listener、Filter、Servlet都有一個初始化的過程,對應的方法分別為:
contextInitialized(ServletContextEvent arg0)
init(FilterConfig filterConfig)
init(ServletConfig config)
那麼它們的初始化順序是什麼呢?
Listener > Filter > Servlet
TestServlet.Java
Java代碼
- package com.cos;
- import Java.io.IOException;
- import Javax.servlet.GenericServlet;
- import Javax.servlet.ServletConfig;
- import Javax.servlet.ServletException;
- import Javax.servlet.ServletRequest;
- import Javax.servlet.ServletResponse;
- public class TestServlet extends GenericServlet {
- @Override
- public void init(ServletConfig config){
- System.out.println("Servlet 初始化 。。。");
- }
- @Override
- public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
- System.out.println("Servlet service 。。。");
- }
- }
TestFilter.Java
Java代碼
- package com.cos;
- 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 銷毀。。。");
- }
- }
TestListener.Java
Java代碼
- package com.cos;
- 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
XML代碼
- <web-app version="2.5" XMLns="http://java.sun.com/XML/ns/Javaee" XMLns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/XML/ns/Javaee/web-app_2_5.xsd">
- <servlet>
- <servlet-name>s< span>servlet-name>
- <servlet-class>com.cos.TestServlet< span>servlet-class>
- < span>servlet>
- <servlet-mapping>
- <servlet-name>s< span>servlet-name>
- <url-pattern>/login< span>url-pattern>
- < span>servlet-mapping>
- <filter>
- <filter-name>f< span>filter-name>
- <filter-class>com.cos.TestFilter< span>filter-class>
- < span>filter>
- <filter-mapping>
- <filter-name>f< span>filter-name>
- <url-pattern>/*< span>url-pattern>
- < span>filter-mapping>
- <listener>
- <listener-class>com.cos.TestListener< span>listener-class>
- < span>listener>
- < span>web-app>